N-Body Simulation Methods
An N-body simulation is a numerical experiment that follows self-gravitating masses as they pull on one another under Newton's law of gravity. The particles may be literal — the stars of a globular cluster — or coarse tracers sampling a smooth phase-space distribution, so a billion of them stand in for a galaxy halo's dark matter. Either way the reason the field exists is stark: the gravitational -body problem has no closed-form solution for , so once you want to know how a star cluster relaxes, how a disk goes bar-unstable, or how the cosmic web grows from a nearly uniform early universe, direct numerical integration is the only route. Three problems then organize everything. The first is arithmetic: gravity couples every particle to every other, so the naive force sum costs per step — fine for the stars of a cluster, hopeless for the particles of a cosmological box; the subject's history is largely the history of cheaper force solvers (Barnes–Hut trees, particle-mesh grids, hybrid TreePM). The second is physical: a real galaxy is collisionless, its relaxation time far longer than its age, yet a coarsely sampled simulation exaggerates graininess, and softening — blurring each point mass over a length — is the fix. The third is geometric: gravity is Hamiltonian, so the integrator must preserve phase-space volume, and the symplectic leapfrog does exactly that, which is why energy errors oscillate instead of drifting over millions of steps.
- An N-body simulation integrates Newton's equations for self-gravitating particles, supplying numerical solutions to the gravitational -body problem where analytic methods fail for .
- Direct summation evaluates all pairwise forces at cost — accurate and appropriate for collisional star clusters, but ruinous for large .
- Tree codes group distant particles into multipoles for cost; particle-mesh solvers put mass on a grid and solve Poisson's equation by FFT at .
- Gravitational softening replaces the singular force with a smoothed kernel, capping the peak pairwise force at and suppressing spurious two-body scattering.
- Symplectic leapfrog integration conserves phase-space volume and holds the energy error bounded over long runs, unlike higher-order Runge–Kutta; method choice follows the physics — collisional systems want direct summation, collisionless systems want tree, PM, or TreePM with softening and large .
- Key idea: every N-body method answers one question — how to evaluate gravitational forces cheaply and accurately — under two constraints: preserve the collisionless mean-field limit through softening, and preserve Hamiltonian structure through symplectic time-stepping.
Every N-body method is an answer to one question — how to evaluate gravitational forces cheaply and accurately — subject to two constraints: preserve the collisionless (mean-field) limit through softening, and preserve Hamiltonian structure through symplectic time-stepping.
Where this lives today
N-body simulation is the workhorse of computational astrophysics, its frontier set by hardware as much as algorithms. Cosmological codes such as GADGET-4, PKDGRAV3, and AbacusSummit now evolve tens of billions to trillions of particles on GPU supercomputers, producing the mock universes that Euclid, DESI, and Rubin's LSST compare against to constrain dark energy and the neutrino mass through the matter power spectrum and halo mass function. On the collisional side, direct codes descended from Aarseth's NBODY6 — on GPUs as NBODY6++GPU and PeTar — model million-star clusters, tracking mass segregation, core collapse, and the assembly of the black-hole binaries whose mergers LIGO and Virgo detect. A stubborn open problem sits between the two traditions: the "final parsec problem" of how a pair of supermassive black holes at a merged galaxy's center sheds its last orbital energy to coalesce, demanding integration accurate enough to resolve individual stellar scatterings yet large enough to hold a whole nucleus.
The physical picture
Every timestep, each particle must answer "who pulls on me, and how hard?" The three great force solvers are three answers. Direct summation asks every other particle, one at a time — honest, exact, and quadratic in cost. A tree notices that a distant clump of a million particles pulls almost exactly like a single point at its center of mass, so it lumps the clump together whenever it subtends a small enough angle. Particle-mesh goes furthest: it forgets individual particles, smears their mass onto a grid, and solves for the potential everywhere at once with one Fourier transform. The first figure sets the three strategies side by side, with the cost each pays.
Softening is a deliberate blurring, and the second figure makes precise what it buys. A true point mass gives an infinite force at zero separation, so two particles that pass close scatter violently, injecting artificial relaxation a real collisionless galaxy never suffers. Replace by the Plummer-softened and the force no longer diverges — it rises, peaks, and turns over, so particles glide past like extended blobs rather than colliding like billiard balls. The peak is capped at the exact value at , and beyond a few the softened and Newtonian curves are indistinguishable.
The leapfrog integrator earns its name from positions and velocities that hop over each other, staggered half a step apart in time — a staggering that makes the scheme time-reversible and symplectic, so the energy error oscillates instead of drifting and an orbit survives millions of steps without spiraling in or out. The deepest tension is statistical: with , each simulation particle carries an enormous mass and its graininess is exaggerated, so the craft of collisionless work is to push high and choose so discreteness relaxation stays negligible while the structures of interest remain resolved.
The core equations
The starting point is Newton's second law with the softened force: each particle is accelerated by the vector sum of the smoothed pulls of all the others. Setting recovers the exact inverse-square law; a finite is what makes the sampled system behave as a collisionless fluid rather than a cloud of scattering point masses.
where: — position of particle ; — mass of particle ; — gravitational constant; — softening length; — number of particles. Reading it: the denominator would be for true point masses; the added is the entire content of softening. The choice of force solver is dictated by how this sum is evaluated, and the three canonical strategies have sharply different asymptotic costs per timestep — the reason the field moved from direct summation to trees and grids as grew.
where: — number of particles; — number of grid cells. Reading it: direct summation touches all pairs, the tree lets each particle see only nodes, and PM cost is set by the FFT on the mesh. A tree decides when to approximate a whole cell by its center of mass with a single geometric test: a cell of width seen from distance is "well separated" if the angle it subtends is small enough.
where: — width of a tree cell; — distance to the cell's center of mass; — opening-angle tolerance, typically –. Reading it: smaller opens more cells, buying accuracy at higher cost; recovers direct summation. Particle-mesh replaces the pairwise sum by solving the field equation on a grid. Poisson's equation is differential in real space but becomes an algebraic multiplication in Fourier space — the shortcut the FFT exploits.
where: — gravitational potential; — grid density; — Fourier transforms; — wavevector of magnitude . Reading it: becomes multiplication by , so dividing mode-by-mode solves for ; the mode is zeroed to subtract the mean density. Time advance uses the kick–drift–kick leapfrog: a half-step velocity kick, a full-step position drift, and a closing half-step kick at the new position. That symmetric structure is what makes it second-order and symplectic.
where: — position and velocity at step ; — acceleration at ; — timestep. Reading it: only one new force evaluation per step is needed (the closing kick is reused as the next opening kick), so leapfrog is as cheap as Euler. The step size is set adaptively from each particle's acceleration, so a particle plunging through a dense region is resolved more finely than one drifting through a void.
where: — timestep of particle ; — accuracy parameter, –; — softening length; — acceleration magnitude. Reading it: has units of time and estimates how long the particle needs to cross a fraction of . Finally, discreteness sets a floor on how collisionless a simulation can be: finite induces an artificial two-body relaxation, the numerical echo of the physical relaxation time.
where: — two-body relaxation time; — crossing time; — number of particles. Reading it: a faithful collisionless run of duration needs large enough that — millions of particles for a Hubble-time integration.
The goal is to show how replacing each point mass by a Plummer sphere of scale turns the divergent Newtonian force into a smooth, bounded one that still reproduces the far field, and to locate exactly where the softened force peaks — the quantitative fingerprint of softening the second figure displays. We start from the softened potential, take its gradient, find the peak, and read off the near and far limits so the cap on close-encounter scattering is explicit.
Step 1. Replace the point-mass potential by the Plummer-softened form , which is finite at the origin, equal to . Why: the singularity that drives unphysical scattering lives in at ; smoothing it there is the whole point.
Step 2. The acceleration is ; using gives . Why: this is the softened force of equation (1), differing from Newton only by the in the denominator.
Step 3. Set on the magnitude ; the derivative's numerator is proportional to , so the force peaks at , where . Why: this finite ceiling is the mechanism — the maximum kick one particle can deliver is bounded, so no close pass runs away.
Step 4. Check the limits: for the term is negligible and (exactly Newtonian); for the force vanishes linearly, , rather than diverging. Why: softening must be invisible on resolved scales and act only below , which these limits confirm. *These two limits — recovering the inverse-square law as and the peak at — are the quantitative fingerprints of Plummer softening.*
Go deeper · Derivation B · 1 minWhy leapfrog conserves energy and Runge–Kutta does not
The goal is to explain the most important fact about time integration in gravitational dynamics: leapfrog, though only second order, keeps the energy error bounded over arbitrarily many orbits, while a higher-order Runge–Kutta scheme with smaller per-step error drifts secularly and corrupts the orbit. The reason is that leapfrog exactly integrates a nearby shadow Hamiltonian — exposed by splitting the evolution operator and applying the Baker–Campbell–Hausdorff expansion — so geometric structure, not formal order, is what matters.
Step 1. Write and the exact one-step evolution as , with the Lie operators of the drift and kick. The KDK leapfrog is the symmetric product . Why: each factor is an exact partial flow, hence symplectic, and a composition of symplectic maps is symplectic — phase-space volume is preserved exactly.
Step 2. The Baker–Campbell–Hausdorff formula gives with , the shadow Hamiltonian. Why: symmetric splitting cancels the odd-order terms, so differs from only at — the numerical orbit exactly solves a small, fixed deformation of the real problem.
Step 3. Because the map is symplectic, is conserved exactly along the numerical orbit, so the true energy oscillates within a band of width and never drifts. Why: this is the payoff — bounded energy error for all time, so a halo runs for a Hubble time without spurious heating.
Step 4. By contrast RK4 has a smaller local error, , but is not symplectic: with no conserved shadow Hamiltonian its energy error accumulates roughly linearly and eventually dominates. Why: for long runs the geometric property beats formal order, which is why production codes integrate with leapfrog, not RK. *The leading energy error scales as and stays bounded for all time — a result that can be confirmed directly by integrating a Kepler orbit over many periods and watching the energy oscillate within a fixed band rather than drift.*
Go deeper · Derivation C · 1 minThe particle-mesh Poisson solve by FFT
The goal is to trace the full particle-mesh cycle that turns a cloud of particles into the force on each one in only operations, by recasting the global gravity problem as a single convolution the FFT performs cheaply. We deposit mass on a grid, transform, multiply by the Poisson Green's function, transform back, and interpolate to the particles — seeing why the mean-density mode is dropped and why deposit and interpolate must share a kernel.
Step 1. Assign mass to the grid: , spreading each particle over nearby grid points with a kernel such as Cloud-In-Cell. Why: the FFT acts on gridded fields, so masses must first become a density at the mesh points.
Step 2. Forward transform at cost , with periodic boundaries automatic in the discrete Fourier basis. Why: in Fourier space the Laplacian is diagonal — a differential operator becomes plain multiplication.
Step 3. Apply the Green's function mode-by-mode, , and set . Why: the mode is the uniform mean density, whose potential diverges as ; zeroing it is the Jeans swindle for a periodic box, leaving only the fluctuation potential that drives the dynamics.
Step 4. Inverse transform for , take (finite differences or in Fourier space), and interpolate back, , with the same kernel as Step 1. Why: identical deposit and interpolate kernels make the grid forces antisymmetric, so total momentum is conserved exactly. *Momentum conservation follows from the shared deposit-and-interpolate kernel; the Green's function follows directly from in Fourier space; and the isolated-mass potential can be cross-checked against Ewald summation.*
Limiting cases
The right method, and the regime in which its output can be trusted, follows from the system's type and scale.
| Case | Result | Meaning |
|---|---|---|
| Collisional (small ) | , – | Star clusters: two-body relaxation is real physics. Use direct summation with adaptive timesteps and regularized close binaries; softening small or zero. |
| Collisionless (large ) | , | Galaxies and dark-matter halos sample the collisionless Boltzmann equation. Use tree, PM, or TreePM with finite softening to suppress artificial relaxation. |
| Cosmological volumes | –, – | Comoving coordinates with in the equations of motion, periodic boundaries via FFT or Ewald summation; TreePM dominates. |
| High dynamic range | Fixed-grid PM under-resolves dense clumps; a tree, TreePM, or adaptive-mesh solve restores small-scale force resolution. |
Worked examples
1 · The cost of a billion-particle step (fully worked)
A flagship run evolves dark-matter particles. Compare the per-step cost of direct summation, a Barnes–Hut tree, and a PM solver on a grid.
Step 1. Direct summation evaluates pairwise terms per step. Even at interactions/s/core that is core-seconds, roughly 1600 core-years for one timestep — and a run needs thousands of steps. Impossible at this .
Step 2. A tree scales as . With the work is node interactions per step, so the speedup over direct is — about 300 million times cheaper per step, turning centuries into seconds.
Step 3. PM cost is the FFT on cells: operations — comparable to the tree but with a smaller prefactor, though forces below one cell are lost, which is why production cosmology uses TreePM (PM long-range, tree short-range). Trees and PM cut operations to , a factor — the entire reason billion-particle cosmology is feasible.
2 · How many particles keep a halo collisionless (fully worked)
A halo has crossing time and must stay faithful over a Hubble time, . How large must be so that numerical relaxation is negligible, ?
Step 1. From equation (7), ; the crossing times cancel, leaving .
Step 2. Solve by trial: gives (too small); gives (enough). So just to keep relaxation below the physics.
Step 3. That is only the discreteness floor. Resolving the halo's cusp, subhalos, and streams demands far more, –. Relaxation sets a hard minimum of , but structural resolution is what pushes real halo runs to –.
3 · Softened force ceiling and the timestep (fully worked)
A Milky-Way-scale run uses and . Find the maximum pairwise acceleration and estimate the timestep from with .
Step 1. From Derivation A the acceleration peaks at . With , the scale , so .
Step 2. Then ; with and the step is — about 1.4% of the crossing time, roughly seventy steps per crossing: fine enough to keep the leapfrog energy error small, coarse enough that a Hubble-time run stays affordable.
Physics of the portrait
N-body simulation has no single founding equation and no single founder, but it has an archetype: the patient builder of direct-summation codes who insisted that gravity be integrated honestly, star by star, for the collisional systems where every close encounter matters.
Origins · 1 minSverre Aarseth and how this was discovered
Sverre Aarseth, born in Norway and for six decades based at the Institute of Astronomy in Cambridge, was the field's great constant. Where cosmologists chased ever-cheaper approximate forces, Aarseth devoted his career to doing the gravitational -body problem exactly — every pairwise force summed directly — because the collisional systems he cared about, open and globular clusters, live and die by the close encounters that approximate methods smear away. Beginning around 1963 he built and freely gave away the NBODY series, inventing much of the machinery that still makes direct integration tractable: individual and hierarchical timesteps so a tight binary does not throttle the whole cluster; the Ahmad–Cohen neighbour scheme splitting fast near forces from slow far forces; and Kustaanheimo–Stiefel regularization, which removes a close binary's singularity by a coordinate change rather than by softening. He rode every wave of hardware — mainframes, the GRAPE boards, GPUs in NBODY6++GPU — to push higher without abandoning exactness. His 2003 monograph and freely shared codes trained several generations, making him the embodiment of the collisional, direct-summation tradition that stands opposite the tree and mesh approximations.
Going further
Texts. Binney and Tremaine, Galactic Dynamics, 2nd ed., Ch. 2 and Appendix C (equations of motion, softening, integrators) · Aarseth, Gravitational N-Body Simulations (2003) · Carroll and Ostlie, An Introduction to Modern Astrophysics, 2nd ed. · Dodelson, Modern Cosmology, 2nd ed. and Ryden, Introduction to Cosmology, 2nd ed. (collisionless Boltzmann context) · Hockney and Eastwood, Computer Simulation Using Particles (1988) · Barnes and Hut, Nature 324, 446 (1986). Key numerical benchmarks: the softened-force peak is at , recovering the inverse-square law in the limit; the PM Green's function follows from ; the leapfrog energy error is bounded via the BCH shadow-Hamiltonian argument; the tree-vs-direct cost ratio is at ; and the collisionless relaxation floor is .
Builds on: Gravitational N-Body Problem · Gravitational Two-Body Problem · Collisionless Boltzmann Equation · Two-Body Relaxation Time · Distribution Function and Phase Space. Leads to: Virial Theorem in Stellar Systems · Galactic Potential Models · Jeans Equations · Orbits in Axisymmetric and Triaxial Potentials.
Ask the tutor: ask me to walk through choosing , , and for a specific system — a globular cluster, a galaxy halo, or a cosmological box — and we will size the run together.
Why not just use direct summation for everything, since it is exact?
Because its cost grows as , and the systems astrophysicists most want to simulate are enormous — Worked Example 1 shows a single direct step for particles would take of order 1600 core-years, while a tree does the same physics 300 million times faster. Direct summation stays the choice only for collisional systems of modest size — clusters of to members — where two-body relaxation is real physics and softening would wrongly erase the close encounters. For galaxies and cosmological volumes, solvers are the only viable option.
How do I choose the softening length ε?
It is a compromise, not a free parameter. Too small and the force is barely capped, so an under-sampled system scatters artificially and its core heats; too large and you smear out real structure below , flattening cusps and dissolving subhalos. A common rule ties to a small fraction of the mean interparticle separation in the densest resolved regions. Crucially it must be chosen jointly with : more particles without smaller wastes resolution, smaller without more particles reintroduces relaxation noise. The honest test is convergence — vary and confirm the result does not.
Isn't a run with 10⁹ particles still absurdly under-sampling a galaxy of 10¹¹ stars?
In number, yes — and in a dark-matter halo the mismatch is far larger still. But that is the whole point of the collisionless framework. The particles are not individual stars; they are Monte Carlo samples of a smooth phase-space distribution function obeying the collisionless Boltzmann equation. What must be faithful is the mean-field potential and its evolution, not the identity of any particle. Softening and large together keep the sampling noise — quantified by the numerical relaxation time of equation (7) — negligible over the run, so the coarse sampling tracks the smooth fluid it represents.
Why leapfrog rather than a high-order Runge–Kutta integrator?
Because for gravity the integrator's geometric structure matters more than its formal order. Leapfrog is only second order and RK4 has a much smaller per-step error, yet leapfrog is symplectic: it exactly integrates a shadow Hamiltonian differing from the true one by , so the energy error oscillates within a fixed band forever. RK4 has no conserved quantity; its energy drifts secularly until, over millions of steps, orbits spiral in or out. Add that leapfrog needs one force evaluation per step against RK4's four, and it is both cheaper and more trustworthy.
How do cosmic expansion and periodic boundaries enter the equations?
Cosmological runs use comoving coordinates: the background expansion is factored out, the scale factor enters the equations of motion, and the particles track only the peculiar motions driven by density fluctuations. The Poisson equation is written for the fluctuation potential, which is why the mode is dropped in the PM solve. Periodic boundaries model an infinite universe with a finite box — a particle leaving one face re-enters the opposite one, enforced by the FFT and by Ewald summation over image lattices in tree codes — so a – box is a fair, homogeneous sample of the cosmos.
How do you know a result is real physics and not a numerical artifact?
By convergence testing and conservation checks, never by trusting a single run. Standard health checks: total energy stays constant (bounded oscillation, no drift), and an equilibrium system satisfies the virial ratio — a Plummer or Hernquist realization should sit still, not relax or evaporate. Then vary , , , and and confirm the result does not change. A feature that weakens as grows or shrinks is discreteness noise, not physics; only what survives convergence can be believed.