N-Body Gravity Simulation: How Planets Dance

Gravity is the simplest force in the universe — one equation, two masses, one distance. Yet the gravitational dance of three or more bodies produces motion so complex it can never be solved analytically. Here is how we simulate it numerically, efficiently, and accurately.

Newton's Law of Universal Gravitation

Every mass in the universe attracts every other mass with a force given by Newton's law:

F = G × m₁ × m₂ / r²

Where G is the gravitational constant (6.674 × 10−11 N m² kg−2), m₁ and m₂ are the masses of the two bodies, and r is the distance between their centres. The force is attractive and acts along the line connecting the two bodies.

For two bodies, this gives a perfectly solvable system. The bodies orbit their common centre of mass in ellipses — Kepler's laws fall out directly. Add a third body and everything changes.

Why N-Body Is Hard: The Three-Body Problem

In 1887, Henri Poincaré proved that the three-body gravitational problem has no general closed-form solution. You cannot write down an equation that gives the position of three gravitating masses at time t given their initial conditions. The system is generally chaotic — small differences in initial conditions lead to completely different long-term trajectories.

This is not a failure of mathematics. It is a fundamental property of the equations. Three bodies gravitationally interacting can exhibit every mode of behaviour: stable orbits, quasi-periodic motion, resonances, chaotic wandering, and ejection of one body to infinity.

The only practical way to predict N-body evolution is numerical integration: take small time steps, compute forces, update velocities and positions, repeat. This is what the simulation does — and what every astrophysics code from solar system models to galaxy simulations does.

The Naive Algorithm: O(n²) Complexity

The straightforward approach to computing gravitational forces is to check every pair of bodies:

for each body i:
    force[i] = (0, 0, 0)
    for each body j ≠ i:
        r = position[j] - position[i]
        dist = length(r)
        force[i] += G * mass[i] * mass[j] / dist² * normalize(r)

This requires n × (n−1) force evaluations per time step — O(n²) complexity. For 100 bodies: 9,900 evaluations. For 1,000 bodies: 999,000 evaluations. For 10,000 bodies: nearly 100 million evaluations. For a real galaxy with 100 billion stars, the naive algorithm is completely infeasible.

Softening to Prevent Singularities

There is a numerical problem lurking in the force equation: when two bodies get very close, r approaches zero and the force diverges to infinity. In reality, stars are not point masses — close encounters involve complex physics. In simulation, we add a softening length ε:

F = G × m₁ × m₂ / (r² + ε²)

This caps the maximum force and prevents numerical explosions during close encounters. The softening length is a simulation parameter — too large and the physics becomes unrealistic; too small and close encounters destabilise the integrator.

Barnes-Hut: Reducing to O(n log n)

In 1986, Josh Barnes and Piet Hut published an algorithm that reduces N-body complexity from O(n²) to O(n log n) — a transformative improvement. The key insight: a distant cluster of many bodies can be approximated as a single body at the cluster's centre of mass. The gravitational error from this approximation is small when the cluster is far away.

The Barnes-Hut algorithm builds an octree (a tree that recursively divides 3D space into eight octants at each node). Each internal node stores the total mass and centre of mass of all bodies in its subtree.

When computing the force on body i, the tree is traversed. At each node, a decision is made based on the ratio s/d — where s is the node's spatial size and d is the distance from body i to the node's centre of mass. If s/d < θ (the opening angle threshold, typically 0.5 to 1.0), the node is treated as a single point mass. Otherwise, the node's children are opened and evaluated individually.

function compute_force(body i, node):
    if node is leaf:
        add direct force from node's body
    else:
        s = node size
        d = distance from i to node's centre of mass
        if s/d < θ:
            add approximate force from node's mass
        else:
            for each child of node:
                compute_force(body i, child)

With θ ≈ 0.5, the error in force estimates is below 1% while computation drops from hours to seconds for the same particle count. Modern cosmological simulations use variants of Barnes-Hut to simulate billions of dark matter particles.

Leapfrog Integration: Stability Over Accuracy

Knowing the forces is only half the problem. You also need to integrate the equations of motion — update positions and velocities — in a way that remains stable over many thousands of time steps.

Simple Euler integration (x += v*dt; v += a*dt) seems natural but has a fatal flaw for orbital mechanics: it does not conserve energy. The total energy of the system drifts upward over time, and orbits slowly spiral outward. Over long simulations, planets escape their stars.

The leapfrog integrator solves this by staggering position and velocity updates by half a time step:

// kick-drift-kick (KDK) form:
v_half = v + a * (dt/2)      // half-step velocity
x = x + v_half * dt           // full-step position
a = compute_forces(x)         // forces at new position
v = v_half + a * (dt/2)       // second half-step velocity

The leapfrog is symplectic — it exactly conserves a modified Hamiltonian close to the true one. In practice this means energy oscillates around the correct value rather than drifting, allowing simulations to run for billions of time steps without accumulating error.

Higher-order integrators (Runge-Kutta 4, Yoshida 6th order) are more accurate per step but require more force evaluations. For gravitational N-body, leapfrog with a small time step is usually the best trade-off.

Real Astrophysics Applications

N-body simulation is a core tool of modern astrophysics:

Explore gravitational dynamics in your browser at /nbody/. Try setting up stable three-body figure-eight orbits, or watch what happens when you add a massive interloper to a planetary system.

The Stability of Our Solar System

Is our own solar system stable? This turns out to be a surprisingly difficult question. Numerical integrations run for billions of simulated years show that the inner planets (Mercury through Mars) have a small but nonzero probability of entering chaotic orbits. Mercury's orbit could become unstable on timescales of a few billion years, potentially colliding with Venus or being ejected.

The outer planets are more stable but not perfectly so. The four-body resonance between Jupiter, Saturn, Uranus, and Neptune means small perturbations can accumulate. The solar system as we know it may be one of many possible configurations that happened to persist long enough for complex life to evolve.

Frequently Asked Questions

What is the N-body problem?

The N-body problem asks how N point masses move under mutual gravitational attraction. For N=2, an exact analytical solution exists (Kepler orbits). For N≥3, no general closed-form solution exists and the system must be solved numerically, integrating Newton's law of gravitation for all pairwise interactions over time.

How does gravitational force scale with distance?

Gravitational force follows an inverse-square law: F = G·m₁·m₂/r². Doubling the distance reduces the force to one-quarter; tripling it reduces force to one-ninth. This means distant bodies have negligible influence while close encounters produce dramatic deflections — the source of the rich dynamics in N-body simulations.

What numerical integration methods are used for N-body simulations?

Common methods include Euler integration (simple but inaccurate), Leapfrog/Verlet integration (good energy conservation, widely used), Runge-Kutta 4 (accurate but computationally expensive), and Symplectic integrators (preserve phase-space volume, ideal for long-term orbital simulations). Leapfrog is the standard choice for gravitational N-body codes.

What is the Barnes-Hut algorithm?

Barnes-Hut is an approximation algorithm that reduces N-body computation from O(N²) to O(N log N) by grouping distant bodies into larger aggregates using an octree (3D) or quadtree (2D). If a cluster of bodies is far enough away relative to its size (the opening angle criterion), it's treated as a single body at its center of mass.

What is gravitational softening?

Gravitational softening replaces the 1/r² force law with 1/(r²+ε²) near r=0, where ε is the softening length. This prevents infinite forces during close encounters, which would cause timestep instabilities. Softening effectively treats particles as extended mass distributions rather than point masses at very small separations.

What causes chaotic behavior in N-body systems?

N-body systems exhibit chaos because close gravitational encounters are extremely sensitive to initial conditions. Small changes in a particle's position or velocity can be amplified by hyperbolic close encounters, leading to completely different long-term trajectories. The Solar System itself is chaotic on timescales of ~5 million years.

What are Lagrange points?

Lagrange points are five special positions in a two-body gravitational system (like Earth-Sun) where a small third body can remain in stable or unstable equilibrium. L1, L2, L3 are unstable saddle points, while L4 and L5 (60° ahead and behind in the orbit) are stable for mass ratios below ~1:25. The James Webb Space Telescope orbits the Sun-Earth L2 point.

How does dark matter affect N-body cosmological simulations?

In cosmological N-body simulations, dark matter particles dominate the mass budget (~85% of all matter). Without dark matter, simulated galaxies rotate too slowly and structures don't form fast enough to match observations. Including dark matter produces rotation curves, halo structures, and large-scale web-like filaments that match observed galaxy surveys.

What is orbital resonance?

Orbital resonance occurs when two bodies have orbital periods in a simple integer ratio (like 1:2, 2:3). Repeated gravitational kicks at the same orbital phases amplify perturbations. Resonances can destabilize orbits (Kirkwood gaps in the asteroid belt) or stabilize them (Pluto-Neptune 2:3 resonance keeps them from colliding).

Can N-body simulations model black hole mergers?

Standard Newtonian N-body codes cannot model black hole mergers because general relativistic effects dominate at small separations. Specialized codes use Post-Newtonian approximations to add relativistic corrections, or full numerical relativity (solving Einstein's field equations on a grid). The gravitational waves detected by LIGO were predicted using such numerical relativity simulations.