Timestep and integrator accuracy
The same equations give different answers depending on the integrator and timestep. Explicit Euler steadily adds energy to an oscillator, semi-implicit Euler keeps energy bounded, and RK4 is far more accurate per step. Every method fails if the timestep is too large.
What it demonstrates
The same equations give different answers depending on the integrator and timestep. Explicit Euler steadily adds energy to an oscillator, semi-implicit Euler keeps energy bounded, and RK4 is far more accurate per step. Every method fails if the timestep is too large.
How it works
Three copies of one system (a 1 kg spring–mass, or a 1 m pendulum) start from the same state and are advanced with the same Δt by explicit Euler, semi-implicit Euler and classic RK4. The spring–mass reference is its exact solution x₀·cos ωt. The pendulum has no elementary closed form, so its reference is RK4 with sub-steps of at most 0.5 ms.
The phase portrait plots position against velocity. Energy conservation makes the exact trajectory a closed loop. For the spring, explicit Euler multiplies the energy by exactly (1 + ω²Δt²) every step. Semi-implicit Euler stays on a slightly distorted closed loop while ω·Δt < 2. RK4 slowly loses energy, but at a rate that is negligible for small ω·Δt.
Playback speed changes how many simulated seconds run per wall-clock second. It does not change the physics, which shows that simulation frequency and real-time execution are separate things.
Adjustable parameters
- System: spring–mass or pendulum
- Timestep Δt (0.001–0.3 s)
- Spring stiffness k (1–50 N/m)
- Pendulum release angle θ₀ (10–170°)
- Playback speed (0.25×, 1×, 4×)
Known limitations
- One degree of freedom. In a full robot, the stiffest element (often contact or a stiff joint) sets the largest stable timestep.
- Real engines also use implicit or partially implicit integrators, for example MuJoCo's implicit-in-velocity options, which this experiment does not show.
Equations
Core update rule
// lib/sim/ch02-integrators.ts
export function eulerStep(s, t, dt, a) {
const acc = a(s.x, s.v, t);
return { x: s.x + s.v * dt, v: s.v + acc * dt };
}
export function semiImplicitStep(s, t, dt, a) {
const v = s.v + a(s.x, s.v, t) * dt; // velocity first
return { x: s.x + v * dt, v }; // then position with the new velocity
}Explained in Chapter 2: Physics Engines