1. The N-body problem

Let point masses have positions and velocities , . Newton’s law of gravitation gives
where is the gravitational constant. Throughout the lesson (and in src/lib/math/nbody.ts) we use
dimensionless units with : once a reference mass and a length are fixed, the unit of
time is .
With momenta , the system is Hamiltonian with
and , . It is separable: depends only on and only on . The ten classical integrals are the energy , the linear momentum , the uniform motion of the center of mass and the angular momentum
For there are not enough additional integrals to solve the problem by quadratures (results of Bruns and Poincaré), so numerical integration is unavoidable. The question is: what structure of the exact flow should a good integrator respect?
2. Two integrators

We write , , and a step of size from to .
2.1 Classical Runge–Kutta (RK4)
Local error and global error on a fixed interval. But RK4 is not symplectic: nothing prevents the energy errors of each step from accumulating with the same sign. The typical outcome in bounded orbits is a secular drift, (with depending on the problem; see exercise 3, where for the harmonic oscillator one gets ).
2.2 Leapfrog (Störmer–Verlet, kick-drift-kick)
Since , the exact flows of and of separately are trivial:
- flow of (kick): ;
- flow of (drift): ,
with . The leapfrog is the symmetric composition (Strang splitting)
that is, in terms of accelerations :
It costs one force evaluation per step (the last one is reused in the next), versus four for RK4. It has three structural properties:
- Symplectic. Each factor is the exact flow of a Hamiltonian, hence symplectic, and the composition of symplectic maps is symplectic (exercise 1). Recall that is symplectic if its Jacobian satisfies with .
- Symmetric (reversible): ; this is why its order is even, here .
- Conserves exactly (up to round-off), because each kick applies pairwise central forces and each drift moves parallel to (exercise 2).
3. Why does the energy not drift? The modified Hamiltonian

Backward error analysis looks for a Hamiltonian whose exact flow coincides with the numerical method. If denotes the Hamiltonian vector field of , the flow of over is and the symmetric Baker–Campbell–Hausdorff formula gives
where the terms of order are double commutators of and . Since the commutator of Hamiltonian vector fields is (up to sign) the field of the Poisson bracket , the method is (formally) the exact flow of
The coefficients are checked on the harmonic oscillator, where everything is explicit (exercise 4). Since is symplectic, the series is Hamiltonian (this is what fails for RK4) and the numerical solution conserves up to exponentially small terms. The precise result (Hairer, Lubich & Wanner, ch. IX, Theorem 8.1, for analytic ) is
with , independent of and . That is: energy error bounded in over exponentially long times, with no drift. The error oscillates (it grows at pericenters and comes back down), but it does not accumulate.
Two honest caveats:
- The constant and the scale depend on how analytic is along the orbit. In a close encounter () the local time scale becomes tiny and a fixed step no longer resolves it: the fixed-step leapfrog loses its guarantees. In practice one uses regularizations (Kustaanheimo–Stiefel), symmetric adaptive steps or specialized integrators.
- A naive adaptive step destroys symplecticity: the map changes from step to step with an .
3.1 Higher order without losing the structure: the Yoshida integrator
The leapfrog is of order 2. Yoshida (1990) observed that, being symmetric (), its expansion in contains only odd powers, , and that a symmetric composition of three steps of sizes , , ,
cancels the term: the first condition guarantees consistency (advancing in total) and the second cancels (the commutators of order add linearly in the to first order). The solution is
The central step is negative and larger than in absolute value: the method goes forward, backward and forward again. It is unavoidable (Suzuki 1991): no composition of positive leapfrog steps exceeds order 2. The result is symplectic and symmetric (composition of symplectic and symmetric maps), of order 4, with 3 force evaluations per step. The same trick iterated gives orders 6 and 8 (Yoshida gives the coefficients), with 7 and 15 leapfrogs per step.
It is in src/lib/math/yoshida.ts. Measurements with our code (test yoshida.test.ts):
| Problem | leapfrog | Yoshida 4 | |
|---|---|---|---|
| Figure-eight, 1 period | 0.02 | ||
| Figure-eight, 1 period | 0.01 | ||
| Figure-eight, 1 period | 0.005 | ||
| Two bodies , 100 periods | 0.03 |
Dividing by 2 divides the leapfrog error by 4 and the Yoshida error by 16: orders 2 and 4. And in the long eccentric orbit both remain bounded (the maximum of the second half does not exceed that of the first), whereas RK4 with the same step ends at and keeps growing. At equal cost (3 evaluations of Yoshida versus 3 leapfrog steps of size , whose error would be ), Yoshida wins by a factor of 4 in this problem, and the advantage grows as is reduced.
3.2 The energy conservation theorem in general
The result of the previous section is not exclusive to order 2. For any symplectic integrator of order applied to an analytic Hamiltonian, with a sufficiently small step (Hairer, Lubich & Wanner, ch. IX, Theorem 8.1),
The proof follows the same path: the method is the exact flow, up to exponentially small terms, of a modified Hamiltonian (optimally truncated), and is conserved exactly by that flow; the difference is bounded on a bounded region of phase space. For Yoshida, : that is what the table shows. The condition “sufficiently small step” is serious: Yoshida has internal steps of size , so its stability limit on the oscillator is instead of (exercise 7).
What to observe. With the scenario “2 bodies, e = 0.8” and “Both overlaid”, the leapfrog error
(solid line) oscillates with peaks at each pericenter but its envelope does not grow; the RK4 error (dashed) starts
smaller over many stretches and grows monotonically until it exceeds it. Raise the speed to see tens of
periods. In the tests of src/lib/math/__tests__/nbody.test.ts (e = 0.7, , 100 periods) the RK4 error
grows linearly with , whereas the leapfrog maximum in the second half does not exceed that of the first.
In our runs the RK4 drift scales approximately as (step multiplies the error
by ), in line with exercise 3.
4. Sensitivity to initial conditions

Let be a solution and another that starts at distance in phase space. The maximal Lyapunov exponent is
If the separation grows as and the orbit is chaotic; is the Lyapunov time. In an integrable system (Kepler) neighboring orbits separate only polynomially (through the difference of periods) and .
Numerically the separation saturates when it stops being small, so the method of Benettin et al. (1980) renormalizes: every interval it measures , accumulates and rescales the neighboring trajectory to distance along the current direction. After intervals,
It is implemented in lyapunovBenettin; the simulator also shows the estimate without renormalization,
(valid while ). The distance used is the Euclidean one in ,
.
How to measure it in practice. Three decisions affect the number that comes out: (1) the renormalization interval must be shorter than the time in which leaves the linear regime () but not so short that round-off noise dominates; (2) must comfortably exceed round-off ( versus ) so that the initial direction of the perturbation is meaningful; (3) is defined as a limit , but the finite-time estimate converges as (law of large numbers over the ) and, in systems that alternate regular stretches and close encounters, it fluctuates strongly from one interval to the next. It must therefore always be given with its integration time and, if possible, averaged over neighboring initial conditions. A useful check: in an integrable system (two bodies) the estimator must decay as toward zero; if it does not, numerical error is being mistaken for chaos. And another: does not depend on the integrator if is small; if it changes when changes (as happens in the Pythagorean problem with versus ), the close encounters are not resolved.
Practical consequence. If we want the state with tolerance starting from an uncertainty , the prediction horizon is
which grows only logarithmically with the initial precision. Not even double-precision round-off () escapes: it is also a perturbation that chaos amplifies. This is why in a chaotic system it makes no sense to ask for the exact trajectory at long times, but rather for statistical or structural properties (energy, final state), and why it matters so much that the integrator respects the conserved quantities.
5. Two paradigmatic solutions

5.1 The figure-eight
Moore (1993) numerically found a periodic orbit in which three equal masses chase one another along the same figure-eight curve; Chenciner and Montgomery (2000) proved its existence by minimizing the action over loops with the symmetries of the eight. With , and the conditions of Simó (2002),
the period is , the angular momentum is zero and the energy is (checked in the tests). Simó showed that it is linearly stable: a perturbation of does not destroy the eight, and in the simulator grows slowly, not exponentially. It is a good test of integrators: after one period the state must return to the initial one (in the tests, to within with ).
5.2 Burrau’s Pythagorean problem
Burrau (1913) posed three masses , and at rest at the vertices of a right triangle with sides , , , each mass opposite the side of equal length. With the coordinates of Szebehely & Peters (1967),
the center of mass is at the origin, and . Burrau could only integrate the beginning by hand; Szebehely and Peters (1967), now with a computer and regularization, showed that after a series of close encounters the system breaks up: around (units ) a last triple encounter occurs and mass is ejected for good, while masses and remain as a binary; Peters extended the integration to to confirm the escape (“elliptic-hyperbolic” motion).
Here the two lessons appear together: the close encounters make the fixed-step leapfrog show spikes in
(try varying ) and the dynamics is chaotic. With our implementation
(lyapunovBenettin, , ) the finite-time estimate is in units
, versus for the circular two-body orbit over (in this case the true value
is and what is measured is the slow decay of the estimate). These are estimates from
our code, not reference values.
Problems
Exercise 1 (symplecticity of the leapfrog). Show that and are symplectic and conclude that is.
Show solution
Proof. The Jacobian of the kick is with symmetric. Then
using . For the drift, and the same computation works because is symmetric. By the chain rule , and if and then .
Exercise 2 (exact conservation of ). Show that the leapfrog conserves for any .
Show solution
Proof. In a kick, the positions do not change and with , parallel to . Thus . In a drift, and . (RK4 does not have this property: its intermediate stages mix positions and velocities from different instants.)
Exercise 3 (RK4 dissipates energy in the oscillator). For , write , so that . Show that RK4 gives with and that
Show solution
Proof. Applying RK4 to gives exactly the degree-4 Taylor polynomial of . With , , and
Since , after steps : a secular drift, linear in for , and unbounded at long times.
Exercise 4 (exact invariant of the leapfrog in the oscillator). Show that the leapfrog applied to is the linear map
which conserves exactly , which is stable if and only if , and that this agrees with of section 3.
Show solution
Proof. Substituting, , and give the matrix with , . Its determinant is (area preserved: symplectic in 1 degree of freedom). With one checks : the entry is , the entry is and the cross entry . Hence is conserved. The eigenvalues satisfy ; they have modulus 1 and are distinct if , that is, , with numerical frequency . On the other hand, with , : , , , and
proportional to up to . The energy error is therefore bounded and of size , exactly what the general theory predicts.
Exercise 5 (predictability horizon). With (units ), by how much does the prediction horizon with tolerance lengthen if we go from to ?
Show solution
Solution. : from to . Ten orders of magnitude of initial precision buy only a factor in time.
Exercise 6 (with the simulator). (a) In the figure-eight with “Both”, set : which integrator keeps the shape of the orbit for more periods? Relate it to section 3. (b) Turn on “Perturb” in the figure-eight and in the Pythagorean problem. Compare how grows in the logarithmic plot: a straight line of slope indicates exponential growth. (c) In the Pythagorean problem, reduce from to . Does the final state change? Why does this not contradict the theorem of section 3? (Hint: close encounters and chaos.)
Show solution
(a) The leapfrog: with ( steps per period) RK4 deforms the eight within a few turns because its energy error accumulates, whereas the leapfrog keeps the shape (although with a growing phase lag along the curve: the phase error does grow; what does not grow is the energy error). (b) In the eight, grows slowly and almost linearly in (polynomial growth: linearly stable orbit); in the Pythagorean problem it grows as a straight line in the logarithmic plot, with jumps at each close encounter: slope . (c) It changes: with the close encounters are not resolved (the local time scale drops below ) and the error in them, amplified by chaos (), leads to a different final state. The theorem requires with set by the analyticity of along the orbit, and in a close encounter becomes tiny; moreover, the theorem bounds the energy, not the trajectory, and in a chaotic system two trajectories with the same energy can end in completely different states.
Exercise 7 (computational: Yoshida). Implement the leapfrog and the order-4 Yoshida integrator for the two-body problem (, , , , ). (a) Reproduce the table of §3.1 by measuring over 100 periods with . (b) Measure the order of both over one period with . (c) Apply Yoshida to the harmonic oscillator , and determine numerically the beyond which the solution blows up; compare it with .
Show solution
Skeleton in Python for (a) and (b):
import numpy as np
w1 = 1/(2 - 2**(1/3)); w0 = -2**(1/3)/(2 - 2**(1/3))
def acel(r): # r: (N,3); global masses m
a = np.zeros_like(r)
for i in range(len(r)):
d = r - r[i]; dist = np.linalg.norm(d, axis=1); dist[i] = np.inf
a[i] = np.sum((m/dist**3)[:, None]*d, axis=0)
return a
def leapfrog(r, v, h):
v = v + 0.5*h*acel(r); r = r + h*v; v = v + 0.5*h*acel(r); return r, v
def yoshida4(r, v, h):
for w in (w1, w0, w1): r, v = leapfrog(r, v, w*h)
return r, v
def energia(r, v):
K = 0.5*np.sum(m*np.sum(v**2, axis=1)); U = 0
for i in range(len(r)):
for j in range(i+1, len(r)): U -= m[i]*m[j]/np.linalg.norm(r[i]-r[j])
return K + UThe initial conditions are taken from dosCuerpos (apocenter: , , shared according to the masses). Expected results: table of §3.1 (leapfrog , Yoshida ), error ratios and when dividing by 2. (c) For the oscillator, the leapfrog matrix with step has eigenvalues of modulus 1 if ; the longest step is , hence Yoshida is stable if . Numerically, with the energy oscillates within bounds and with it grows exponentially. It is the price of the negative step: order 4 buys precision in exchange for 40% less stability margin.
✦ Self-assessment
Further reading
- Hairer, Lubich & Wanner (2006), Geometric Numerical Integration: ch. I (examples and leapfrog), §II.4–II.5 (composition and splitting methods: construction of Yoshida), ch. VI (symplectic integrators), ch. IX (backward error analysis; Theorem 8.1 on energy conservation).
- Yoshida (1990), Phys. Lett. A 150, 262: the coefficients of orders 4, 6 and 8 and the proof by BCH.
- Chenciner & Montgomery (2000), Ann. Math. 152, 881, and Simó (2002): existence and stability of the eight. Moore (1993), PRL 70, 3675: its numerical discovery.
- Szebehely & Peters (1967), AJ 72, 876: the complete solution of the Pythagorean problem, with the figures of the ejection.
- Benettin, Galgani, Giorgilli & Strelcyn (1980), Meccanica 15, 9: the renormalization method for Lyapunov exponents.
- Aarseth, S. J. (2003), Gravitational N-Body Simulations, chs. 1–2: the N-body specialist’s point of view on integrators and regularization.
🍎 Teacher guide
- Time
- 2 classes of 90 min plus a 2-hour programming workshop
- Learning outcome
- By the end, the student proves that the leapfrog is symplectic and conserves angular momentum, explains through the modified Hamiltonian why its energy error stays bounded, constructs the order-4 Yoshida integrator, and numerically estimates the Lyapunov exponent of a three-body system while interpreting its limitations.
- Evidence of learning
- Submission of exercise 7 (implementation of leapfrog and Yoshida with error table and measured order) and of exercise 6 (report with simulator screenshots and the estimate of λ for the Pythagorean problem with two different steps).
Materials
- Python 3 with NumPy and Matplotlib
- Reference code: src/lib/math/nbody.ts, yoshida.ts and their tests
- The portal's N-body simulator
- The papers of Chenciner–Montgomery (2000) and Szebehely–Peters (1967), for optional reading
Suggested sequence
Class 1 (90 min). Opening (15 min): the N-body problem as a Hamiltonian system; the ten integrals. Development (60 min): RK4 and leapfrog; proof of symplecticity (exercise 1) and conservation of L (exercise 2) on the board; the modified Hamiltonian and the statement of the energy conservation theorem; check on the oscillator (exercise 4). Closing (15 min): simulator with “2 bodies, e = 0.8”, compare the energy-error curves.
Class 2 (90 min). Opening (10 min): “can one have order 4 and symplecticity?”: construction of Yoshida (§3.1). Development (55 min): Lyapunov exponent, Benettin’s method, predictability horizon (exercise 5); the eight and the Pythagorean problem, with their stories. Closing (25 min): exercise 6 with the simulator; mini-quiz.
Workshop (2 h). Full exercise 7: leapfrog and Yoshida, error table, measured order and stability limit. Extension for those who finish: estimate λ of the Pythagorean problem with Benettin’s method and two values of h.
Common mistakes
- Believing that a high-order method conserves energy better at long times than a low-order symplectic one. The table of §3 (RK4 versus leapfrog over 100 periods) refutes it; insist that order and structure are independent properties.
- Confusing energy error with trajectory error. The leapfrog conserves the energy but its phase error grows linearly; in the eight it shows up as a lag along the curve.
- Taking a finite-time estimate of λ as “the” Lyapunov exponent. Always ask for the integration time, the dependence on h and the check with an integrable system.
- Thinking that the negative step of Yoshida is a mistake. Show Suzuki's theorem: with positive steps one cannot go beyond order 2.
- Using an adaptive step with a symplectic method and expecting the energy to stay bounded. Refer to the next lesson (Runge–Kutta and adaptive step).