Algorithmintro
Direct N-body summation
Also called particle-particle method, direct summation.
Computes the force on each of N particles by summing over all other particles, in O(N^2) time per step and with no approximation error.
- Time
- Θ(N^2) worst
- Space
- Θ(N) extra
- Where
- N = the number of particles
- Model
- Real RAM
- Properties
- deterministic
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Sebastian von Hoerner, Sverre J. Aarseth, 1960
Direct N-body summation computes the gravitational acceleration of each of bodies as the sum of the pull of every other body. It visits each of the pairs once, and it uses Newton's third law to give the force on both bodies of the pair. The result is exact up to rounding, so it is the reference against which the approximate methods (Barnes-Hut, the fast multipole method, particle-mesh) are measured. Its cost grows as , so it is used for star clusters and planetary systems with up to about a million bodies, and on special hardware or GPUs. It is the force part of a solution of the gravitational N-body problem; an integrator such as Hermite or leapfrog moves the bodies.
In plain words
Each body pulls on each other body. The pull is stronger for a heavier body and weaker for a body that is far away. To find the total pull on one body, add up the pulls of all the others, one at a time.
Do this for every body and you have the forces. The work is one small calculation for each pair of bodies. A pair pulls with equal strength in opposite directions, so one calculation gives the pull on both bodies of the pair. With a thousand bodies there are about half a million pairs, and doubling the number of bodies makes four times the work. Nothing is left out, so the answer is exact except for rounding.
The problem
The input is masses and positions , the gravitational constant ( in code units) and a softening parameter . The output is the acceleration of each body and the potential energy,
With this is Newtonian gravity, and two bodies must not be at the same point. With it is Plummer gravitational softening. In both cases .
The algorithm
DIRECT-SUM(m, x, epsilon, G) ▷ N bodies- 1
for i ← 1 to N do a_i ← 0; U ← 0 - 2
for i ← 1 to N - 1 do - 3
for j ← i + 1 to N do - 4
d ← x_j - x_i - 5
s ← |d|² + epsilon² - 6
w ← G / (s √s) - 7
a_i ← a_i + m_j w d - 8
a_j ← a_j - m_i w d ▷ Newton's third law - 9
U ← U - G m_i m_j / √s - 10
return a, U
Lines L2 and L3 visit each unordered pair once. Line L6 computes the common factor of the pair, with the softened distance . Lines L7 and L8 add the pair to both bodies with opposite signs. One pair costs one square root, one division and about 20 other operations in 3D.
Example
Take three bodies in the plane , with and : at , at and at . The distances are 3, 4 and 5, so each factor is rational.
| pair | added to | added to | added to | ||
|---|---|---|---|---|---|
| (1, 2) | (3, 0) | 1/27 | (2/9, 0) | (-1/9, 0) | -2/3 |
| (1, 3) | (0, 4) | 1/64 | (0, 3/16) | (0, -1/16) | -3/4 |
| (2, 3) | (-3, 4) | 1/125 | (-9/125, 12/125) | (6/125, -8/125) | -6/5 |
The sums are , , and . As a check, .
Correctness
Each unordered pair is visited exactly once by lines L2 and L3, and the pair adds the term of to and the term of to . So after line L10 each holds the sum over all , and holds the sum over all pairs. The pair terms of lines L7 and L8 are and , so in exact arithmetic , and the total momentum is conserved by any integrator that uses these forces at one common time. The full proof, with the gradient identity, is in the proof file.
Proof: Direct summation gives the exact accelerations, the potential energy and zero total forcefull
We use exact real arithmetic, as in the real RAM model. Let , masses , positions , and . If , we assume that no two positions are equal. For a pair write , and . Then , and .
Claim 1 (the loop computes the sums). After line L10, for each , and .
Proof. Lines L2 and L3 run over the pairs with , and each such pair occurs exactly once. Consider a fixed body . The pairs that change are the pairs with , at line L7, and the pairs with , at line L8. Line L7 for the pair adds . Line L8 for the pair adds . So each adds its term exactly once, and starts at by line L1. Line L9 adds the term of each pair to exactly once, and starts at .
Claim 2 (force is minus the gradient). For each , .
Proof. Only the pairs that contain depend on . For the pair of and , the term of is , and . So
So minus the gradient of this term is . The sum over is by Claim 1.
Claim 3 (zero total force). .
Proof. By Claim 1, . Group the terms in pairs . The two terms of a pair are and , so they cancel.
Consequences. Claim 1 is the definition of the softened (or, for , the Newtonian) accelerations, so the algorithm has no truncation error. By Claim 3, an integrator that updates all velocities with forces computed at one common time changes the total momentum by per kick. In floating-point arithmetic the two terms of a pair are computed from the same rounded and , but the sums are rounded in different orders, so Claim 3 holds only up to rounding.
Cost. The inner body of lines L4 to L9 runs times, and each run costs a constant number of operations for a fixed dimension. Line L1 costs . So the time is for all inputs, and the extra space is the accelerations.
Complexity
In the real RAM model, the loop of lines L2 and L3 runs exactly times, and each pass costs operations in a fixed dimension. So one force evaluation costs in every case, with no dependence on the positions. The extra space is for the accelerations; no pair list is stored.
For there are 499500 pairs. A run of steps with one force evaluation per step costs . A force evaluation that reads every mass and position needs time, and no exact method below is known for this sum with arbitrary real positions in this model. The tree and multipole methods trade a controlled error for or time.
Properties
- No truncation error. The only errors are rounding errors. The order of the additions changes the result in the last bits, and the total momentum is conserved only up to rounding (see the floating-point model).
- Symmetric. Lines L7 and L8 give equal and opposite pair forces, so there is no spurious net force, unlike tree codes where the forces of on and of on come from different approximations.
- Simple to vectorize and to parallelize. All pairs are independent except for the sums. Each processor can take a block of targets and loop over all sources ; this costs pair evaluations, twice as many, but needs no write conflicts.
Variants and improvements
- All targets, all sources. Loop over all for each without the third law. This doubles the work, but each target is written by one thread only; it is the usual form on GPUs.
- Ring scheme. On processors, each holds bodies, and the blocks of sources travel around a ring of processors, so that each block meets each other block once (Aarseth 2003, Section 3.7).
- Jerk with the force. The Hermite integrator also needs the time derivative of each pair force; it is computed in the same loop with a few more operations per pair.
- Neighbor schemes. The Ahmad-Cohen scheme computes the force of near neighbors often and the force of distant bodies less often (Aarseth 2003, Section 3.2). It is still direct summation, but with two time scales.
- Softening. With the same loop gives the Plummer softened force, used for collisionless systems.
When to use it
Use direct summation when every close encounter matters, as in star clusters, the cores of galaxies with black holes, and planetary systems. Use it as the reference to measure the error of a tree code or an FMM. Use it when is below a few thousand, because there the tree methods have more overhead than they save. For collisionless systems with millions of bodies, use Barnes-Hut, FMM, particle-mesh or TreePM instead.
Pitfalls
- Self-interaction. The pair must be skipped. With it gives no force but adds to the energy.
- Coincident bodies with . Two bodies at the same point give a division by zero. Real close encounters with need regularization, not a tiny time step.
- Counting pairs twice in the energy. If the loop runs over all ordered pairs, the potential energy must be halved.
- The cost of the square root. The square root and the division dominate the cost of a pair. Compute once and form from it.
- Rounding in large sums. For large , the sum of many small far terms with a few large near terms loses digits. Compensated or pairwise summation reduces this when it matters (Kahan summation, pairwise summation).
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/direct-n-body-summation/. The authors are listed in prov/14GKBC.jsonl.
"""Direct N-body summation of gravitational accelerations and potential energy.
The bodies have masses m[i] and positions x[i] (tuples of any dimension,
usually 3). The softening parameter eps gives the Plummer pair potential
-G m_i m_j / sqrt(r^2 + eps^2); eps = 0 is Newtonian gravity. Units: G = 1
unless given.
Each of the N(N - 1) / 2 pairs is visited once, and Newton's third law gives
the force on both bodies of the pair.
Cost: N(N - 1) / 2 pair evaluations, Theta(N^2) time, Theta(N) extra space.
"""
import math
from typing import Sequence
Vec = tuple[float, ...]
def direct_sum(m: Sequence[float], x: Sequence[Vec], eps: float = 0.0, G: float = 1.0) -> tuple[list[list[float]], float]:
"""Return (accelerations, potential energy) by summation over all pairs."""
n = len(m)
dim = len(x[0]) if n else 0
a = [[0.0] * dim for _ in range(n)] # @line L1
u = 0.0
e2 = eps * eps
for i in range(n - 1): # @line L2
xi, ai = x[i], a[i]
for j in range(i + 1, n): # @line L3
xj, aj = x[j], a[j]
d = [xj[k] - xi[k] for k in range(dim)] # @line L4
s = sum(c * c for c in d) + e2 # @line L5
if s == 0.0:
raise ValueError("two bodies at the same point with eps = 0")
r = math.sqrt(s)
w = G / (s * r) # @line L6
for k in range(dim):
ai[k] += m[j] * w * d[k] # @line L7
aj[k] -= m[i] * w * d[k] # @line L8
u -= G * m[i] * m[j] / r # @line L9
return a, u # @line L10
def accelerations(m: Sequence[float], x: Sequence[Vec], eps: float = 0.0, G: float = 1.0) -> list[list[float]]:
return direct_sum(m, x, eps, G)[0]
def potential_energy(m: Sequence[float], x: Sequence[Vec], eps: float = 0.0, G: float = 1.0) -> float:
return direct_sum(m, x, eps, G)[1]
def kinetic_energy(m: Sequence[float], v: Sequence[Vec]) -> float:
return 0.5 * sum(mi * sum(c * c for c in vi) for mi, vi in zip(m, v))
def leapfrog(m: Sequence[float], x: Sequence[Vec], v: Sequence[Vec], h: float, steps: int, eps: float = 0.0, G: float = 1.0) -> tuple[list[list[float]], list[list[float]]]:
"""Kick-drift-kick leapfrog (velocity Verlet) driven by direct_sum. Used to test the forces in motion."""
x = [list(p) for p in x]
v = [list(q) for q in v]
a = accelerations(m, x, eps, G)
for _ in range(steps):
for i in range(len(m)):
for k in range(len(x[i])):
v[i][k] += 0.5 * h * a[i][k]
x[i][k] += h * v[i][k]
a = accelerations(m, x, eps, G)
for i in range(len(m)):
for k in range(len(x[i])):
v[i][k] += 0.5 * h * a[i][k]
return x, v
test_direct_n_body_summation.py 104 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/direct-n-body-summation/. The authors are listed in prov/14GKBC.jsonl.
import math
import random
import pytest
from direct_n_body_summation import accelerations, direct_sum, kinetic_energy, leapfrog, potential_energy
def brute(m, x, eps=0.0, G=1.0):
"""Independent reference: for each body, loop over every other body (no third law)."""
n, dim = len(m), len(x[0])
acc = []
for i in range(n):
ai = [0.0] * dim
for j in range(n):
if j != i:
d = [x[j][k] - x[i][k] for k in range(dim)]
r2 = sum(c * c for c in d) + eps * eps
for k in range(dim):
ai[k] += G * m[j] * d[k] / r2 ** 1.5
acc.append(ai)
u = -0.5 * sum(G * m[i] * m[j] / math.sqrt(sum((x[i][k] - x[j][k]) ** 2 for k in range(dim)) + eps * eps)
for i in range(n) for j in range(n) if i != j)
return acc, u
def random_bodies(n, seed):
rng = random.Random(seed)
m = [rng.uniform(0.5, 2.0) for _ in range(n)]
x = [tuple(rng.uniform(-1.0, 1.0) for _ in range(3)) for _ in range(n)]
return m, x
def test_hand_example_345():
m = [1.0, 2.0, 3.0]
x = [(0.0, 0.0, 0.0), (3.0, 0.0, 0.0), (0.0, 4.0, 0.0)]
a, u = direct_sum(m, x)
want = [(2 / 9, 3 / 16, 0.0), (-1 / 9 - 9 / 125, 12 / 125, 0.0), (6 / 125, -1 / 16 - 8 / 125, 0.0)]
for ai, wi in zip(a, want):
for c, w in zip(ai, wi):
assert c == pytest.approx(w, abs=1e-15)
assert u == pytest.approx(-157 / 60, rel=1e-15)
@pytest.mark.parametrize("eps", [0.0, 0.05])
def test_against_brute_force(eps):
m, x = random_bodies(60, 7)
a, u = direct_sum(m, x, eps)
b, ub = brute(m, x, eps)
scale = max(math.sqrt(sum(c * c for c in bi)) for bi in b)
for ai, bi in zip(a, b):
for c, w in zip(ai, bi):
assert abs(c - w) <= 1e-12 * scale
assert u == pytest.approx(ub, rel=1e-12)
def test_total_force_is_zero():
m, x = random_bodies(80, 3)
a = accelerations(m, x)
big = max(mi * math.sqrt(sum(c * c for c in ai)) for mi, ai in zip(m, a))
for k in range(3):
assert abs(sum(mi * ai[k] for mi, ai in zip(m, a))) <= 1e-12 * big * len(m)
def test_force_is_minus_gradient_of_energy():
m, x = random_bodies(12, 11)
eps, hstep = 0.1, 1e-6
a = accelerations(m, x, eps)
for i in range(len(m)):
for k in range(3):
xp = [list(p) for p in x]
xm = [list(p) for p in x]
xp[i][k] += hstep
xm[i][k] -= hstep
grad = (potential_energy(m, xp, eps) - potential_energy(m, xm, eps)) / (2 * hstep)
assert -grad / m[i] == pytest.approx(a[i][k], rel=1e-6, abs=1e-8)
def test_circular_orbit_period_two_pi():
# Two bodies of mass 1/2 at distance 1: G M = 1, relative speed 1, period 2 pi.
m = [0.5, 0.5]
x = [(-0.5, 0.0, 0.0), (0.5, 0.0, 0.0)]
v = [(0.0, -0.5, 0.0), (0.0, 0.5, 0.0)]
steps = 2000
h = 2 * math.pi / steps
x1, v1 = leapfrog(m, x, v, h, steps)
for p, q in zip(x1, x):
assert math.dist(p, q) < 1e-4
e0 = kinetic_energy(m, v) + potential_energy(m, x)
e1 = kinetic_energy(m, v1) + potential_energy(m, x1)
assert e0 == pytest.approx(-0.125, rel=1e-15)
assert abs(e1 - e0) / abs(e0) < 1e-10
def test_coincident_bodies_need_softening():
m = [1.0, 1.0]
x = [(0.0, 0.0, 0.0), (0.0, 0.0, 0.0)]
with pytest.raises(ValueError):
direct_sum(m, x)
a, u = direct_sum(m, x, eps=0.5)
assert a == [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]
assert u == pytest.approx(-2.0)
History
Von Hoerner published direct integrations of small star clusters on a digital computer in 1960. Aarseth wrote the NBODY codes from the 1960s on, with individual time steps, neighbor schemes and regularization, all built around a direct force sum (Aarseth 2003, Section 1.2). Hockney and Eastwood call the method the particle-particle (PP) method and compare it with mesh methods.
References
- Sverre J. Aarseth, Gravitational N-Body Simulations, Tools and Algorithms, Cambridge University Press, 2003, Sections 1.2 and 1.3 (history and basic concepts), Section 3.7 (ring scheme)
- Roger W. Hockney and James W. Eastwood, Computer Simulation Using Particles, Adam Hilger, 1988, the particle-particle (PP) method
- Sebastian von Hoerner, Die numerische Integration des N-Korper-Problemes fur Sternhaufen. I, Zeitschrift fur Astrophysik 50, 1960, 184-214, the first direct integrations of star clusters
Where this leads
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 14GKBC Edit this page History Report an error Markdown