1. Motivation: from three bodies to a billion

In the previous lesson we integrated three bodies. A globular cluster has – stars; a modern cosmological simulation, particles. The acceleration of each body,
requires terms, so each force evaluation costs pairs: . With that is interactions per step; at interactions per second, eight minutes per step, and a simulation needs – steps. Barnes and Hut (1986) showed that by grouping distant bodies into “pseudo-particles” the cost drops to with a controllable error: it is the algorithm that, with refinements (high-order multipoles, fast multipole methods, meshes), lies behind almost all numerical galactic and cosmological dynamics.
In this lesson (and in src/lib/math/barneshut.ts) we use dimensionless units with . For the Plummer model we also adopt Hénon units: total mass , total energy , so that the scale radius is .
2. The Barnes–Hut idea: monopole approximation

2.1 Potential of a distant group
Let a group of bodies with masses at positions , with total mass and center of mass , be contained in a cell of side . Its potential at a point at distance from the center of mass, with and , is
where are the Legendre polynomials and the angle between and (expansion valid for ). The first three terms are:
- (monopole): .
- (dipole): , identically zero because by definition of the center of mass.
- (quadrupole): , of size .
Therefore, when the group is replaced by a single mass at (monopole approximation), the relative error of the potential is and that of the force, by differentiation, is also . Choosing the center of mass as the center of the expansion is what kills the dipole and makes a parameter as simple as control the error quadratically.
2.2 The octree
The system is enclosed in a cube that is recursively subdivided into 8 octants until each cell contains at most one body. Each internal cell stores its total mass and its center of mass (accumulated during insertion). Construction costs on average and the tree is rebuilt at each step (Barnes & Hut did it that way; it is cheaper than maintaining it).
2.3 Opening criterion
To compute the force on body the tree is traversed from the root. At each cell of side whose center of mass is at distance from the body:
- if (the cell looks “small”), its monopole is used and we do not descend;
- otherwise, the cell is opened and its children are visited;
- a leaf with a single body is treated exactly.
is the opening parameter. With no cell is accepted and the algorithm degenerates into direct summation (our test checks it to ). Usual values: –. The original Barnes–Hut criterion uses the side and the distance to the center of mass; Salmon and Warren (1994) showed that it can fail for cells whose center of mass is close to the edge, and proposed adding to the offset of the center of mass from the geometric center; our implementation uses the original criterion.
2.4 Cost
Proposition. For a given body and a system of bodies distributed with bounded density, the number of cells accepted with the criterion is .
Proof (sketch). The cells at level have side . A cell at that level is accepted if it is at distance and its parent was opened, that is, . The accepted cells of level therefore live in a spherical shell of radii and , of volume , which contains at most cells of volume . Since there are const non-empty levels (the depth of the tree is for bounded density), the total is . Summing over the bodies: .
The dependence is harsh: going from to multiplies the cost by 8. In our table (§5) the measured ratio between and is , less than 8 because at many interactions are with individual leaves, not with cells.
3. Gravitational softening

3.1 Why it is needed
With finite , two bodies can come arbitrarily close and the force diverges: the time step would have to become tiny and, worse, a “collision” between two simulation particles represents nothing physical when each particle stands for stars or a chunk of dark matter. The potential of each particle is replaced by that of a Plummer sphere of radius :
It is exactly the potential generated by the Plummer (1911) density, (exercise 3). The force is finite everywhere: its maximum, , occurs at (exercise 4). This same is the eps parameter of accelerations in integrators.ts and of the whole barneshut.ts module.
3.2 Bias and noise
The price is a bias: for ,
the force is underestimated by (% at , % at : sesgoPlummer). Dehnen (2001) analyzes the trade-off: a large reduces the noise of the force (the fluctuations due to the finite number of neighbors, which scale as for the short-range forces) but increases the bias; there is an optimal that decreases with approximately as – for the Plummer profile, and compact-support kernels (splines) are preferable to the Plummer one because their bias vanishes exactly for . A practical rule: of the order of the mean separation between neighbors in the densest region; in our Plummer sphere with that mean distance to the nearest neighbor is (Hénon units).
4. The virial theorem

4.1 Statement and proof
Let be the scalar moment of inertia. Differentiating twice,
where is the kinetic energy and is the virial of Clausius. For pairwise forces directed along , grouping pairs,
If derives from a homogeneous potential of degree (), , and , the total potential energy. Averaging over time for a bounded system ():
(Binney & Tremaine §4.8.)
4.2 The virial with softening
With Plummer the force is not homogeneous of degree , and the virial of the force differs from the softened potential energy:
So the correct relation in equilibrium is , not ; the difference is positive and of order . virial() returns the three quantities. In our Plummer sphere (): with , , , (the 0.6% deviation from 1 is sampling noise; the theoretical values are , ). With , and : the naive condition gives and the correct one gives : the system, generated in Newtonian equilibrium, is 8% “too hot” for the softened gravity and will expand slightly when integrated. With () the discrepancy rises to 40%: such a softening no longer simulates the same system.
4.3 Use as a diagnostic
In a simulation one monitors (in addition to , and ):
- oscillates around 1 with period dynamical time: system in equilibrium.
- Sustained : hot system, it expands; : it collapses. A system in cold collapse () “violently relaxes” toward in a few dynamical times (Lynden-Bell 1967).
- Secular drift of with constant : two-body relaxation (evaporation, core collapse), a physical effect in clusters but spurious in simulations of collisionless systems, where it signals too small or too small.
5. Numerical results

All from barneshut.ts on Plummer spheres generated with modeloPlummer (seed 7), ; the relative error of each body is .
5.1 Cost and error as a function of ()
| Interactions per body (BH) | Direct () | Saving | Median error | Maximum error | |
|---|---|---|---|---|---|
| 250 | 144 | 249 | 1.7 | ||
| 500 | 231 | 499 | 2.2 | ||
| 1000 | 358 | 999 | 2.8 | ||
| 2000 | 530 | 1999 | 3.8 | ||
| 4000 | 738 | 3999 | 5.4 | ||
| 8000 | 958 | 7999 | 8.4 |
When is multiplied by 32 (250 → 8000) the interactions per body are multiplied by 6.7, whereas direct summation is multiplied by 32. The growth is faster than pure (which would give ) because at these the Plummer profile, highly concentrated, makes a large fraction of the interactions be with leaves; the asymptotic regime is only reached at much larger , when the depth of the tree dominates over the interactions with leaves. The maximum error grows with : there is always some body for which a cell lies right at the limit of the criterion; this is the case that motivated the Salmon and Warren correction.
5.2 Error as a function of ()
| Interactions per body | Median error | Maximum error | |
|---|---|---|---|
| 0.2 | 1326 | ||
| 0.3 | 969 | ||
| 0.5 | 530 | ||
| 0.7 | 319 | ||
| 1.0 | 179 | ||
| 1.5 | 93 |
The median error scales approximately as between and (the monopole prediction is per cell, but the number of accepted cells also grows with and the errors add with random signs). With there are bodies whose force is completely wrong (error 150%): the criterion has accepted cells that contain the body’s own nearest neighbor.
5.3 What precision is needed
A relative force error of per particle and per step, with random signs, accumulates after steps as : in steps, 10%. But the discretization noise (using particles to represent a continuum) already produces force errors of order (Dehnen 2001): for , . It makes no sense to compute the force much better than that intrinsic noise: hence – is the standard.
What to observe. The simulator uses direct summation (three bodies do not justify a tree). With the “Pythagorean” scenario, turn on softening with and compare the evolution with that of : the close encounters that eject mass 3 are damped and the final state changes. It is the most direct demonstration that is a physical parameter of the model, not a numerical detail.
Problems
1. (Quadrupole). Show that for a group of masses with center of mass at the origin the quadrupole term of the potential at is , and that for a cubic cell of side centered on the center of mass it is bounded in absolute value by . Conclude that the relative error of the monopole potential is and, with , below 19% in the worst case.
Show solution
From and the expression follows. Inside a cube of side centered on the center of mass, , hence and the term is bounded by . Relative to the monopole : . With : % as a worst-case bound on the potential; the typical error is much smaller (the table gives a median of %) because the masses are rarely all at the corners and the errors from different cells partially cancel. The force (derivative) has a bound of the same order with a different constant.
2. (Zero dipole). Show that if the expansion is made around a point other than the center of mass (for example, the geometric center of the cell), a dipole term of relative error appears, and compute how much worse it is with .
Show solution
With , , and the term is , of relative size . Compared with the quadrupole , with the dipole is versus : more than twice, and it decays only linearly with distance. This is why the center of mass (and not the geometric center) is the center of the expansion. It is an application of the general principle: the dipole can always be made to vanish by choosing the origin; not so the quadrupole.
3. (Plummer density). Show, with Poisson’s equation , that the potential corresponds to , and check that .
Show solution
In spherical symmetry . With : , , and . Hence and , which is the required expression. Mass: (the integral equals : substitute ). 50% of the mass lies inside (equation ). In Hénon units, with , one obtains and, by the virial theorem, , : the values the test uses.
4. (Maximum force). Show that is maximal at with value , and deduce a lower bound on the time step of a stable leapfrog, .
Show solution
. Substituting: . The maximum local “frequency” of an encounter is , and the stability of the leapfrog for an oscillator requires (previous lesson, exercise 4): . This is the true practical reason for softening: it bounds the time step from below. With and (our sphere with ), .
5. (Virial with softening). Prove the identity and conclude that : a system in Newtonian equilibrium always looks “hot” to the softened gravity.
Show solution
For a pair, . Writing : . Summing over pairs gives the identity; the second term is positive, hence and, both being negative, . A system with has . In our model: with , in agreement with the table. To correct it, the velocities are generated with the softened potential or is rescaled by .
6. (Computational: tree in 2D). Implement a quadtree for bodies in the plane, with criterion , and measure (a) the number of interactions per body for with ; (b) the median error against direct summation for . Compare with the tables of §5.
Show solution
Minimal structure in Python (recursive; for it takes seconds):
import numpy as np
class Celda:
def __init__(self, cx, cy, s):
self.cx, self.cy, self.s = cx, cy, s
self.m = 0.0; self.X = 0.0; self.Y = 0.0 # accumulated mass and center of mass
self.cuerpo = None; self.hijos = None
def insertar(self, i, x, y, m):
if self.m == 0 and self.hijos is None: # empty leaf
self.cuerpo, self.m, self.X, self.Y = i, m, x, y; return
if self.hijos is None: # occupied leaf: subdivide
self.hijos = [None]*4; j = self.cuerpo; self.cuerpo = None
mj, xj, yj = self.m, self.X, self.Y; self.m = 0
self._bajar(j, xj, yj, mj)
self._bajar(i, x, y, m)
self.X = (self.X*self.m + x*m)/(self.m+m); self.Y = (self.Y*self.m + y*m)/(self.m+m); self.m += m
def _bajar(self, i, x, y, m):
k = (x >= self.cx) + 2*(y >= self.cy); q = self.s/4
if self.hijos[k] is None:
self.hijos[k] = Celda(self.cx + (q if k & 1 else -q), self.cy + (q if k & 2 else -q), self.s/2)
self.hijos[k].insertar(i, x, y, m)
def fuerza(c, i, x, y, theta, eps, cont):
if c.m == 0 or c.cuerpo == i: return np.zeros(2)
dx, dy = c.X - x, c.Y - y; d = np.hypot(dx, dy)
if c.hijos is None or c.s < theta*d:
cont[0] += 1; return c.m*np.array([dx, dy])/(d*d + eps*eps)**1.5
return sum(fuerza(h, i, x, y, theta, eps, cont) for h in c.hijos if h is not None)The root is built with the square that contains all the bodies and fuerza is called for each one. Expected results: the number of interactions per body grows slowly (in 2D the factor is instead of ), and the median errors with are of order , as in 3D. The error must vanish with : it is the first test to pass.
7. (Computational: violent relaxation). Generate a Plummer sphere with and halve all the velocities (). Integrate with leapfrog (, , ) up to and plot , and the half-mass radius. In how many dynamical times is reached?
Show solution
With modeloPlummer, leapfrogBarnesHut and virial from barneshut.ts (or the Python version of problem 6). The dynamical time of the sphere is in Hénon units. The system collapses: rises above 1 (rebound) and is damped toward 1 in about –, that is, –: Lynden-Bell’s violent relaxation. The half-mass radius drops to of the initial one and the system ends up more concentrated and with an extended envelope; must be conserved at the 1% level (the error comes from and from the step); if not, reduce or . A small fraction of particles may escape ().
✦ Self-assessment
Further reading
- Barnes & Hut (1986), Nature 324, 446: the original four-page paper, readable in full.
- Aarseth (2003), Gravitational N-Body Simulations, ch. 6: tree codes in the context of direct methods; ch. 1 for the setup.
- Dehnen (2001), MNRAS 324, 273, and Dehnen & Read (2011), EPJ Plus 126, 55: the modern review of softening, trees, fast multipoles and individual time steps.
- Binney & Tremaine (2008), Galactic Dynamics, §2.9 (numerical solution of Poisson’s equation: trees, meshes) and §4.8 (Jeans equations and virial); §2.2.2 for the Plummer sphere.
- Aarseth, Hénon & Wielen (1974), A&A 37, 183: the sampling algorithm for the Plummer model that
modeloPlummeruses. - Salmon, J. K. & Warren, M. S. (1994). Skeletons from the treecode closet. J. Comput. Phys. 111, 136–155: the failures of the original criterion and the criteria with a guaranteed error bound.
🍎 Teacher guide
- Time
- 2 classes of 90 min plus a 2-hour programming workshop
- Learning outcome
- By the end, the student justifies the O(N²) cost of direct summation and the O(N log N) of the tree, derives the error of the monopole approximation, explains the role of softening and uses the virial theorem as a diagnostic of a simulation.
- Evidence of learning
- Submission of problem 6 (2D tree with θ = 0 verification and cost and error tables) and of problem 7 (plots of Q(t), E(t) and half-mass radius with interpretation).
Materials
- Python 3 with NumPy and Matplotlib
- Reference code: src/lib/math/barneshut.ts and its test
- The Barnes & Hut (1986) paper, for prior reading
- The portal's N-body simulator (Pythagorean scenario with and without softening)
Suggested sequence
Class 1 (90 min). Opening (15 min): how much a step of direct summation costs for and why “a bigger computer” is not enough. Development (60 min): multipole expansion and vanishing of the dipole (§2.1), construction of the tree on the board with 8–10 points in 2D, opening criterion, proposition on the cost. Closing (15 min): problem 2 in pairs.
Class 2 (90 min). Opening (10 min): demonstration of the simulator with and without softening. Development (55 min): Plummer potential and Poisson’s equation (problem 3), force bias, virial theorem with and without softening (§4), reading of the tables of §5. Closing (25 min): problems 4 and 5; mini-quiz.
Workshop (2 h). Full problem 6 (2D tree) with the verification as first milestone, and problem 7 with the diagnostic plots. Students who finish can add the quadrupole term and measure how much the error drops at equal .
Common mistakes
- Thinking that ε is a “numerical trick” with no consequences. Show the change of final state of the Pythagorean problem and the virial ratio 1.08 with ε = 0.1: ε defines the system being simulated.
- Making the multipole expansion around the geometric center of the cell. Ask for problem 2 before programming.
- Believing that a force error of 0.3% is “too much” or “too little” without comparing it with the discretization noise N^(−1/2). Discuss §5.3.
- Diagnosing equilibrium with 2K/|W| instead of 2K/|𝒱ε| when there is softening. It is problem 5.
- Confusing violent relaxation (collisionless, fast) with two-body relaxation (collisional, slow). Ask for the time scales of each.