Physics and numerical methods¶
Equations of motion¶
Each body \(i\) has mass \(m_i\), position \(\mathbf r_i\) and velocity \(\mathbf v_i\). Newton’s law of gravitation gives
where \(\epsilon\) is the optional softening length (0 by default).
Softening keeps the force finite when two bodies pass very close to each
other. That avoids huge velocity kicks, at the cost of slightly changing the
physics at distances below \(\epsilon\).
The accelerations of all bodies are computed together with NumPy array operations. The cost grows as \(N^2\), which is fine for up to a few hundred bodies.
Integrators¶
The time step \(h\) is dt. The last step is shortened so the run ends
exactly at final_time.
Euler (--method euler, 1st order):
\(\mathbf r \leftarrow \mathbf r + h\mathbf v\),
\(\mathbf v \leftarrow \mathbf v + h\mathbf a(\mathbf r)\).
It is the simplest scheme, but energy drifts quickly and orbits spiral out. It
is mainly for comparison.
RK2 / midpoint (--method rk2, 2nd order): evaluates the derivative at
the middle of the step.
RK4 (--method rk4, 4th order, default): the classic Runge-Kutta method
with four evaluations per step. The error per unit time scales as \(h^4\),
so halving dt makes it about 16 times smaller.
Checking accuracy¶
The total energy
is conserved by the exact equations. The code records it at every saved frame
(Trajectory.energy) and reports the relative drift
\(|E_\text{end} - E_0| / |E_0|\).