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

\[\dot{\mathbf r}_i = \mathbf v_i, \qquad \dot{\mathbf v}_i = -G \sum_{k \neq i} m_k \frac{\mathbf r_i - \mathbf r_k}{\left(|\mathbf r_i - \mathbf r_k|^2 + \epsilon^2\right)^{3/2}}\]

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

\[E = \sum_i \tfrac12 m_i |\mathbf v_i|^2 - G \sum_{i<k} \frac{m_i m_k}{\sqrt{|\mathbf r_i - \mathbf r_k|^2 + \epsilon^2}}\]

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|\).