Numerical simulation of the gravitational N-body problem. Three integrators are implemented and compared: naive Euler, vectorized Euler, and 4th-order Runge-Kutta (RK4). The main simulation runs in real-time via a Tkinter canvas.
The N-body problem governs the motion of N point masses under mutual Newtonian gravitation. The equation of motion for body i is:
d²rᵢ/dt² = G · Σⱼ≠ᵢ mⱼ (rⱼ − rᵢ) / |rⱼ − rᵢ|³
This system of 3N coupled second-order ODEs has no closed-form solution for N ≥ 3 and requires numerical integration.
The state vector (positions and velocities) is advanced at each step using:
k1 = f(tₙ, yₙ)
k2 = f(tₙ + dt/2, yₙ + dt·k1/2)
k3 = f(tₙ + dt/2, yₙ + dt·k2/2)
k4 = f(tₙ + dt, yₙ + dt·k3)
yₙ₊₁ = yₙ + (dt/6)(k1 + 2k2 + 2k3 + k4)
RK4 achieves O(dt⁴) local truncation error, substantially outperforming explicit Euler — O(dt) — for long-time orbital integration.
A first-order explicit integrator, included for numerical comparison.
| File | Description |
|---|---|
n_body_RK4.py |
Real-time N-body simulation with RK4, Tkinter visualization |
n_body_vecto.py |
Vectorized Euler integration |
n body pb.py |
Naive Euler implementation |
EULER_RK4.py |
Side-by-side accuracy comparison of Euler vs. RK4 |
numpy
tkinter (included in standard Python)
Install:
pip install numpypython n_body_RK4.pyA Tkinter window opens showing N bodies evolving under mutual gravity in real time. By default, one central massive body orbited by N−1 satellites in circular initial orbits is initialized.
| Parameter | Default | Description |
|---|---|---|
n |
4 | Number of satellite bodies |
G |
6.67×10⁻¹¹ | Gravitational constant (SI) |
dt |
0.005 | Integration time step |
r_orbit |
100 px | Initial orbital radius |
- Press, W. H. et al. (2007). Numerical Recipes (3rd ed.). Cambridge University Press.
- Aarseth, S. J. (2003). Gravitational N-Body Simulations. Cambridge University Press.