HomeAlgorithms & AIBarnes–Hut N-body

🌌 Barnes–Hut N-body

Interactive Barnes–Hut N-body simulator: live quadtree, theta-criterion descent, velocity-Verlet integration, and a naive O(n^2) speed comparison.

Algorithms & AI3DAdvanced60 FPS
barnes-hut ↗ Open standalone

About the Barnes-Hut N-Body Algorithm

The gravitational N-body problem — computing the force on every particle due to every other particle — naively requires O(n²) calculations per time step, which becomes prohibitively expensive for large n. The Barnes-Hut algorithm (1986) reduces this to O(n log n) by recursively subdividing space into a quadtree (in 2D) or octree (in 3D) and treating clusters of distant bodies as a single centre-of-mass when the ratio s/d (cell size s to distance d) falls below a threshold angle θ. It is the backbone of modern galaxy-formation codes such as GADGET and is used in every cosmological simulation of structure formation in the Universe.

This simulation lets you vary the body count N (up to 2,000), the opening angle θ (0 = exact, 1.5 = very approximate), gravitational softening ε, and time step dt across four initial presets: gas cloud, two merging galaxies, central mass + cloud, and a ring. Enabling the quadtree overlay shows which cells are approximated (cyan) and which are recursed (pink) for a highlighted body, making the trade-off between speed and accuracy immediately visible.

Frequently Asked Questions

What is the N-body problem?

The gravitational N-body problem asks: given N point masses with known initial positions and velocities, compute their future positions under mutual Newtonian gravity F = Gm₁m₂/r². For N = 2 the solution is a conic section (Kepler orbit); for N ≥ 3 no general closed-form solution exists and numerical integration is required. Each time step naively costs O(n²) force evaluations, making large simulations — modelling millions of stars — impractical without an approximation algorithm.

How does the Barnes-Hut quadtree work?

At each time step the algorithm inserts all bodies into a quadtree — a recursive partition of 2D space into four equal squares. To compute the force on body i, the tree is traversed from the root: if a node's cell is "far enough" away (s/d < θ, where s is the cell width and d is the distance to i), the entire cell is approximated by its total mass and centre of mass. Otherwise the node is opened and its children are tested. This reduces the typical number of interactions from O(n) per body to O(log n).

What does the opening angle θ control?

θ (theta) is the key accuracy/speed parameter. At θ = 0 every cell is always opened regardless of distance, reproducing the exact O(n²) direct sum. At θ = 0.5 (a common production value) the algorithm is about 95 % as accurate as direct summation while running roughly 30–100× faster for n = 1,000. At θ = 1.5 speed is maximal but distant galaxy structure is noticeably smeared. The simulation displays the live speed-up ratio so you can observe this trade-off directly.

What is gravitational softening (ε)?

Gravitational softening replaces the 1/r² force law with 1/(r² + ε²), which prevents the force from diverging to infinity when two bodies come very close together. Without softening, close encounters would require an infinitesimally small time step to integrate accurately, making the simulation crash or produce nonsensical "slingshot" velocities. The softening length ε is typically set to a fraction of the mean inter-particle separation; in real cosmological simulations it is around 1 kpc for dark-matter particles.

Why is the Barnes-Hut algorithm O(n log n)?

The quadtree has O(n) nodes and depth O(log n). For each of the n bodies the tree traversal visits O(log n) nodes on average before enough cells satisfy the θ criterion. Multiplying gives O(n log n) force evaluations per step. Building the tree itself also costs O(n log n). In practice the constant factors are small, and for n = 10,000 the speed-up over O(n²) is around 100–1,000-fold.

What happens during two-galaxy merger presets?

When two galaxies pass through each other, tidal forces strip stars from the outskirts and fling them into long "tidal tails" and bridges that stretch across millions of light-years. The process is governed almost entirely by gravity; the stellar discs pass through each other largely unimpeded because stars are so widely spaced. The Milky Way and Andromeda galaxies are on a collision course and are expected to merge in about 4.5 billion years, producing a similar tidal tail structure visible in this preset.

How does the speed-up compare to naïve O(n²) in practice?

The simulation displays the Barnes-Hut evaluation count alongside the naïve n(n–1)/2 comparisons needed for direct summation. For n = 500 and θ = 0.7, Barnes-Hut typically evaluates around 3,000–5,000 force pairs per body per step instead of 499, giving a 50–100× speed-up. As n grows the advantage compounds: at n = 2,000 the naïve method needs nearly 2 million pair evaluations per step while Barnes-Hut needs only around 20,000.

What is kinetic and potential energy, and why do they fluctuate?

Kinetic energy KE = Σ ½mᵢvᵢ² and gravitational potential energy PE = –Σᵢ≠ⱼ Gmᵢmⱼ/rᵢⱼ (summed over all pairs). In a true conservative simulation total energy E = KE + PE should be constant, but numerical integration introduces errors. The leapfrog (Verlet) integrator used here is symplectic, meaning it conserves a modified Hamiltonian and keeps long-term energy drift very small. Fluctuations you see are partly genuine physical exchanges (e.g. a body in an eccentric orbit swaps KE and PE) and partly numerical truncation error from finite dt.

What is the "sensitivity to initial conditions" highlight?

When you tick "Highlight θ-descent for picked body", clicking a body shows which quadtree cells it approximates vs recurses. The same quadtree cell may be treated differently for bodies at different positions, illustrating that Barnes-Hut is an adaptive algorithm. For chaos in the actual N-body trajectories, use the two-trajectory comparison in related simulations: even a Δ = 10⁻⁵ perturbation to initial conditions leads to exponentially diverging paths, demonstrating that the N-body problem is in general chaotic.

Is the Barnes-Hut algorithm used in real astrophysics codes?

Yes — the GADGET code family (Springel 2001, 2005) uses a hierarchical tree very similar to Barnes-Hut and has been used to simulate the Millennium Simulation (10 billion particles) and the IllustrisTNG galaxy formation runs. Modern codes often combine Barnes-Hut with fast-multipole methods (FMM), particle-mesh (PM) techniques, or GPU parallelism to simulate up to 10¹² particles. The algorithm is also used outside astrophysics, in molecular dynamics, fluid simulation, and rendering of dense particle systems.

What does "centre of mass" mean in the quadtree context?

Each internal node of the quadtree stores the total mass M = Σmᵢ and the mass-weighted average position r_cm = Σmᵢrᵢ / M of all bodies within that cell. When a distant cell is approximated, the gravitational force on body i is computed as if all that cell's mass were concentrated at r_cm. This single-pole approximation is accurate to first order in s/d; higher-order multipole expansions (quadrupole, octopole) can be included for better accuracy at the cost of more storage and computation.

⚙ Under the hood

The Barnes–Hut algorithm approximates an N-body gravity simulation in O(n log n) using a quadtree and a θ accuracy criterion. Watch the tree adapt to clusters and force evaluations plummet vs naïve O(n²).

Canvas 2DBarnes-HutQuadtreeN-BodyAlgorithms

3D · Three.js / WebGL renderer · 60 FPS target · runs fully client-side, no install

What did you find?

Add reproduction steps (optional)