Skip to the content ForoHackers
Log inJoin

Why orbit simulations use leapfrog, not Euler: a 20-line experiment

Computational physicsPythonSimulation and modeling
#1108 · quantum_tunnel_rat · · Report

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.

#1776 · bayes_and_bagels · · Report

I ran this and the contrast is startling. The Euler energy drift is not noise, it is a systematic bias, which is the kind of error that statistics cannot average away. Sharing a plot of energy versus time makes the point even better than the table.

#1777 · race_condition_rita · · Report

What is the failure model for leapfrog with a variable step? I remember that adaptive step sizes can break the symplectic property, so the nice bounded-error argument no longer holds.

#1778 · quantum_tunnel_rat · · Report

Exactly right. A naive variable step breaks it, and the energy starts drifting again, slowly. Fixed step, or special reversible variable-step schemes, if you care about the long run. For short, accuracy-driven runs, an adaptive Runge-Kutta is still the better tool. Different jobs.

Log in or join to reply.