Sub topic 15
Simulating an orbit step by step
The earlier chapters gave closed-form results for circular orbits and Kepler's laws. This chapter shows how to get the same motion from a computer, with no formula for the path. You only need the inverse-square acceleration and a loop. The chapter assumes you know Newton's second law, the gravitational acceleration a = -GM r̂ / r², specific orbital energy, and angular momentum. It also assumes basic Python.
Why simulate at all
For two bodies the path is a conic section, and you can write it down exactly. Add a third body, thrust, or atmospheric drag, and no general closed form exists. Nearly all real orbit work, from mission design to galaxy models, uses numerical integration.
The two-body case is the best place to learn the technique. You already know the exact answer, so you can tell when the simulation is wrong.
The idea: small steps of constant acceleration
Acceleration depends on position, and position changes as the body moves. A simulation freezes time into small steps of length dt. In each step it treats the acceleration as constant, then updates velocity and position. It then recomputes the acceleration at the new position and repeats.
The loop is only as good as the update rule in the middle. The next two sections compare two rules.
Setting up the physics
Work in a plane, with the central mass at the origin. Use GM directly, because Earth's product GM = 3.986004 × 10¹⁴ m³/s² is known more precisely than G or M alone. The acceleration is
- a_x = -GM x / r³
- a_y = -GM y / r³
where r = √(x² + y²). Dividing by r³ rather than r² folds the unit vector r̂ = (x, y)/r into the same expression.
A naive method: explicit Euler
Explicit Euler uses the old acceleration to update velocity, and the old velocity to update position:
- v_new = v + a·dt
- x_new = x + v·dt
It is easy to write, and it is wrong in a way that matters. Over one step the body moves along the tangent to its path, never along the curve. The tangent always lies outside a circle, so each step lands slightly farther out. The error is systematic, so it accumulates.
A better method: leapfrog
Leapfrog (also called velocity Verlet) takes half a velocity step, a full position step, then another half velocity step using the new acceleration:
- v ← v + ½·a(x)·dt
- x ← x + v·dt
- v ← v + ½·a(x)·dt
It costs one acceleration evaluation per step, the same as Euler once you reuse the acceleration from the end of one step as the start of the next. It is second-order accurate, which means halving dt cuts the per-orbit error by about four, where Euler's drops only by two.
Leapfrog is also symplectic. It does not conserve the true energy exactly. It conserves a nearby "shadow" energy, so the computed energy oscillates in a narrow band instead of drifting. Over thousands of orbits this is the property that matters most.
| Property | Explicit Euler | Leapfrog |
|---|---|---|
| Order of accuracy | First | Second |
| Acceleration evaluations per step | 1 | 1 (reused) |
| Energy over many orbits | Drifts steadily | Oscillates in a bounded band |
| Typical use | Teaching what not to do | Orbits and other long-running conservative systems |
Running both methods
This program integrates the same circular low Earth orbit with both rules. The initial speed is the circular speed √(GM/r), which is about 7.67 km/s at this radius. The orbital period is about 5544 s, so 6000 s covers a little more than one orbit.
import math
GM = 3.986004e14 # Earth's G*M in m^3/s^2
def accel(x, y):
r3 = (x * x + y * y) ** 1.5
return -GM * x / r3, -GM * y / r3
def energy(x, y, vx, vy):
# specific orbital energy (energy per unit mass)
return 0.5 * (vx * vx + vy * vy) - GM / math.hypot(x, y)
def euler_step(state, dt):
x, y, vx, vy = state
ax, ay = accel(x, y)
return x + dt * vx, y + dt * vy, vx + dt * ax, vy + dt * ay
def leapfrog_step(state, dt):
x, y, vx, vy = state
ax, ay = accel(x, y)
vx += 0.5 * dt * ax
vy += 0.5 * dt * ay
x += dt * vx
y += dt * vy
ax, ay = accel(x, y)
vx += 0.5 * dt * ax
vy += 0.5 * dt * ay
return x, y, vx, vy
def run(step, dt, t_end, r0):
state = (r0, 0.0, 0.0, math.sqrt(GM / r0))
e0 = energy(*state)
for _ in range(int(t_end / dt)):
state = step(state, dt)
x, y, vx, vy = state
e1 = energy(*state)
return math.hypot(x, y) - r0, abs((e1 - e0) / e0)
r0 = 6.771e6
for name, step in (("euler", euler_step), ("leapfrog", leapfrog_step)):
dr, drift = run(step, 5.0, 6000.0, r0)
print(f"{name:9s} radius change: {dr:12.1f} m energy drift: {drift:.2e}")The Euler radius grows by roughly a hundred kilometers in this run, and its energy drifts upward by a visible fraction. Leapfrog's radius change is far smaller and its energy error is orders of magnitude lower. A true circular orbit has zero radius change, so any nonzero value is numerical error.
Checking results with conserved quantities
Gravity is a central force, so two quantities must stay constant for the real motion:
- Specific energy, E = ½v² - GM/r.
- Specific angular momentum, L = x·vy - y·vx.
Neither is input to the integrator. Leapfrog never sees E or L, so if they hold steady, the dynamics are being followed correctly. This is a much stronger test than eyeballing a plot.
You can also check against Kepler. From E you get the semi-major axis a = -GM/(2E), and the period T = 2π√(a³/GM). Run for exactly T, and the body should return near its starting point.
Choosing the time step
The step must be small compared with how fast the motion changes. A rough rule is to use a few hundred to a thousand steps per orbit for leapfrog on a circular orbit.
Eccentric orbits are harder. Near perigee the body moves fastest and the acceleration changes quickest, so a step that is fine at apogee can be too coarse at perigee. The symptoms are a perigee that slowly rotates (precession that Newtonian gravity does not predict for two bodies) and a visible energy wobble.
Floating point also limits you. Double precision carries about 16 digits, and each step adds rounding error. Millions of steps accumulate it, which sets a floor on the energy accuracy.
Edge cases to watch
- Units. Mixing kilometers and meters turns GM into nonsense. Pick SI units and keep them throughout.
- Starting at the origin. The acceleration divides by r³, so r = 0 is a division by zero. Real bodies have a radius, so stop the run on impact.
- Close encounters. The 1/r² force grows quickly at small r, and a fixed step then fails badly. This is the usual reason N-body codes soften the force or use adaptive schemes.
- Wrong sign. A positive sign in accel pushes the body away from the center. The orbit then flies off in a straight-ish line, which is easy to spot.
Exercise
The circular orbit above has a period of about 5544 s, and the step is dt = 5 s. About how many leapfrog steps cover one orbit, and what would you expect to happen to the energy error if you doubled dt to 10 s?
Show answer
One orbit takes about 5544 / 5 ≈ 1109 steps. Leapfrog is second-order, so doubling dt makes the error about four times larger. The energy would still oscillate in a bounded band instead of drifting, but the band would be roughly four times wider.
Exercise
A student starts at r0 = 6.771e6 m with speed 1.2 times the circular speed. Without running code, will the orbit be a circle, an ellipse, or an escape path? Which conserved quantity would you use to confirm the simulation, and what should its value do over time?
Show answer
The escape speed is √2 ≈ 1.414 times the circular speed, so 1.2 times gives a bound ellipse, with the start point at perigee. Specific energy E = ½v² - GM/r is negative and should stay nearly constant. Specific angular momentum L = x·vy - y·vx should also stay nearly constant, and a steady drift in either one points to a bug or a step that is too large.