Simulate a planet on a circular orbit around a star (units where GM = 1, radius 1, speed 1). Total energy per unit mass should stay at -0.5 forever. Let us see what two integrators do over 1000 time units with step dt = 0.01.
import math
def acc(x, y):
r3 = (x * x + y * y) ** 1.5
return -x / r3, -y / r3
def energy(x, y, vx, vy):
return 0.5 * (vx * vx + vy * vy) - 1.0 / math.hypot(x, y)
def euler(n, dt):
x, y, vx, vy = 1.0, 0.0, 0.0, 1.0
for _ in range(n):
ax, ay = acc(x, y)
x += vx * dt; y += vy * dt
vx += ax * dt; vy += ay * dt
return x, y, vx, vy
def leapfrog(n, dt):
x, y, vx, vy = 1.0, 0.0, 0.0, 1.0
ax, ay = acc(x, y)
for _ in range(n):
vx += 0.5 * dt * ax; vy += 0.5 * dt * ay
x += vx * dt; y += vy * dt
ax, ay = acc(x, y)
vx += 0.5 * dt * ax; vy += 0.5 * dt * ay
return x, y, vx, vy
Results after 100000 steps:
| Method | Final energy | Final radius |
|---|---|---|
| Euler | about -0.127 | about 3.85 |
| Leapfrog | -0.4999999997 | 1.00001 |
Explicit Euler adds energy at every step, so the planet spirals outward and the "orbit" is a lie. Leapfrog is symplectic: it does not conserve the energy exactly, but it conserves a nearby "shadow" Hamiltonian, so the error stays bounded and oscillates instead of drifting. That is the property you want for anything that runs for millions of steps: planetary systems, molecular dynamics, accelerators.
Same cost per step as Euler, one extra force evaluation if you do it naively, none if you reuse the acceleration like above. There is no excuse.