CodeRigor

LESSON

Integrators and energy

Step a spring with explicit Euler, symplectic Euler and velocity Verlet, watch their energy, measure their order, and run them from a fixed timestep.

A simulation advances a state by small steps, and the rule for taking one step decides whether the result stays believable. This lesson is about three such rules for a mass on a spring, and about the energy they keep or lose. This lesson pairs with 01 - Writing a physics simulation in 10 minutes by Ten Minute Physics, linked under Watch & read. The video covers a first simulation loop, integration methods and substepping; you build the integrators, measure their errors and write the fixed-timestep loop that drives them. The second video listed there, on constraints, is a good follow-up once your steps run.

The state is a position x and a velocity v. The force gives an acceleration a(x) that depends on position only. For a spring with stiffness k and mass m, a(x) = -(k/m)·x and the energy is ½·m·v² + ½·k·x². A real spring never changes its energy, so any change you see is the integrator's doing.

Three rules cover most of what you need. Explicit Euler updates both numbers from the old state: x′ = x + v·dt and v′ = v + a(x)·dt. Symplectic Euler, also called semi-implicit Euler, changes one line: update the velocity first, then move the position with the new velocity. Velocity Verlet moves the position with a second-order term, evaluates the acceleration again at the new position, and averages the two accelerations to update the velocity.

Energy of a spring over 40 steps
Spring with k = 4, m = 1, dt = 0.1, starting at x = 1 with v = 0, so the true energy stays at 2. Explicit Euler climbs, symplectic Euler wobbles around 2, Verlet is nearly flat.
Energy of a spring over 40 steps
Spring with k = 4, m = 1, dt = 0.1, starting at x = 1 with v = 0, so the true energy stays at 2. Explicit Euler climbs, symplectic Euler wobbles around 2, Verlet is nearly flat.

Take one step by hand with k = m = 1, dt = 0.5, starting at x = 1, v = 0, so the energy is 0.5. The acceleration is -1. Explicit Euler gives v′ = -0.5 and, using the old velocity 0, x′ = 1; its energy is 0.625. Symplectic Euler gives the same v′ but moves with it, so x′ = 0.75 and the energy is 0.40625. Verlet gives x′ = 1 + 0 - ½·1·0.25 = 0.875, then a(x′) = -0.875 and v′ = ½·(-1 - 0.875)·0.5 = -0.46875; its energy is about 0.49268, the closest to 0.5.

Python
def energy(x, v):
    return 0.5 * v * v + 0.5 * x * x       # k = m = 1

x, v, dt = 1.0, 0.0, 0.5
a = -x
v_new = v + a * dt
verlet_x = x + v * dt + 0.5 * a * dt * dt
verlet_v = v + 0.5 * (a + -verlet_x) * dt
print("explicit ", x + v * dt, v_new, energy(x + v * dt, v_new))
print("symplectic", x + v_new * dt, v_new, energy(x + v_new * dt, v_new))
print("verlet   ", verlet_x, verlet_v, round(energy(verlet_x, verlet_v), 5))

For the spring the explicit method has an exact law: every step multiplies the energy by 1 + (k/m)·dt². With dt = 0.1 and k/m = 4 that factor is 1.04, so 100 steps turn an energy of 2 into 2·1.04¹⁰⁰, about 101. That is growth without bound, and shrinking dt only slows it. The other two do not drift this way: their energy stays inside a narrow band however long you run.

Python
def run(step, n=100, dt=0.1):
    x, v, low, high = 1.0, 0.0, 9e9, 0.0
    for _ in range(n):
        x, v = step(x, v, dt)
        e = 2 * v * v / 4 + 2 * x * x       # 0.5*v*v + 0.5*4*x*x
        low, high = min(low, e), max(high, e)
    return round(e, 3), round(low, 3), round(high, 3)

a = lambda x: -4 * x
explicit = lambda x, v, dt: (x + v * dt, v + a(x) * dt)
symplectic = lambda x, v, dt: (x + (v + a(x) * dt) * dt, v + a(x) * dt)
def verlet(x, v, dt):
    xn = x + v * dt + 0.5 * a(x) * dt * dt
    return xn, v + 0.5 * (a(x) + a(xn)) * dt
for step in (explicit, symplectic, verlet):
    print(run(step))

Energy is one measure. Accuracy is another: compare the position at t = 1 with the exact solution cos(ωt), where ω = √(k/m), and halve dt. An error that halves means the method is first order, one that drops to a quarter means second order. Both Euler methods are first order. Verlet is second order, and it is also time reversible: run it forward, flip the sign of v, run the same number of steps, and you land on the start.

The loop that calls the integrator needs the same care. A frame lasts however long it lasts, but the physics wants a fixed dt. Keep an accumulator: add the frame time, take as many whole steps as fit, and carry the remainder to the next frame. Cap the number of steps per frame. Without a cap, one slow frame owes many steps, those steps make the next frame slower, and the program never recovers. With a cap you drop the backlog and accept that the simulation briefly runs slow.

One frame of a fixed-timestep loop
The accumulator holds time that has passed but not yet been simulated. The cap protects the loop from a frame that owes too many steps.
One frame of a fixed-timestep loop
The accumulator holds time that has passed but not yet been simulated. The cap protects the loop from a frame that owes too many steps.

Two mistakes recur. In symplectic Euler, writing the position update with the old velocity turns the method back into explicit Euler, and the energy starts to climb; the update order is the whole method. In velocity Verlet, reusing the acceleration from the start of the step instead of evaluating it at the new position leaves the position right and the velocity wrong. The run still looks plausible for a while, but the second-order accuracy and the reversibility are gone, and the energy grows. A constant force such as gravity cannot expose that mistake, because the acceleration never changes with position, so test with a spring.

Three kinds of evidence verify the code here. The exact solution of the spring, the closed-form growth factor of explicit Euler and the error ratio when dt is halved are all independent of your implementation. The reversibility test needs no reference at all. What they do not show is that the spring is the right model: a force that depends on velocity, or a very stiff force with a large dt, behaves differently, and a bounded energy says nothing about whether the phase of the motion is right.

Watch & read

Free lectures, talks and readings that cover this skill from another angle. All resources →