UniversityAdvancedPhysicsOscillationsProgramming

How do you simulate a pendulum in code?

Turn the pendulum equation into a state you can step forward in time. Compare explicit Euler, semi-implicit Euler and RK4 with real energy-drift numbers, in JavaScript.

How do you simulate a pendulum in code?

Write the state as two numbers — the angle θ\theta and the angular velocity ω\omega — and advance them in small time steps using the acceleration −gLsin⁡θ-\frac{g}{L}\sin\theta. The choice of integrator matters more than it looks: explicit Euler makes the pendulum gain energy without limit, while semi-implicit Euler and RK4 keep it stable.

Key fact
Update the velocity first, then the position with the new velocity (semi-implicit Euler) — or use RK4. Never use plain explicit Euler on an oscillator: its energy grows every step.

From one equation to a state you can step

This article is the code companion to How a pendulum works, where the equation θ¨=−gLsin⁡θ\ddot\theta = -\frac{g}{L}\sin\theta is derived. A computer steps first-order systems, so introduce ω=θ˙\omega = \dot\theta:

{θ˙=ωω˙=−gLsin⁡θ\begin{cases}\dot\theta = \omega \\[2pt] \dot\omega = -\dfrac{g}{L}\sin\theta\end{cases}

Each step of length Δt\Delta t moves (θ,ω)(\theta,\omega) a little forward. The three integrators below differ only in how they do that.

Three integrators in a few lines

javascript
const g = 9.81, L = 1;
const accel = (theta) => -(g / L) * Math.sin(theta);

// Energy per unit mass — used to check each method
const energy = ({ theta, omega }) =>
  0.5 * L * L * omega ** 2 + g * L * (1 - Math.cos(theta));

// 1. Explicit Euler: both updates use the OLD state
function explicitEuler(s, dt) {
  const a = accel(s.theta);
  s.theta += s.omega * dt;
  s.omega += a * dt;
}

// 2. Semi-implicit Euler: velocity first, then position with the NEW velocity
function semiImplicitEuler(s, dt) {
  s.omega += accel(s.theta) * dt;
  s.theta += s.omega * dt;
}

// 3. Classic 4th-order Runge–Kutta
function rk4(s, dt) {
  const f = (th, om) => [om, accel(th)];
  const [k1t, k1o] = f(s.theta, s.omega);
  const [k2t, k2o] = f(s.theta + 0.5 * dt * k1t, s.omega + 0.5 * dt * k1o);
  const [k3t, k3o] = f(s.theta + 0.5 * dt * k2t, s.omega + 0.5 * dt * k2o);
  const [k4t, k4o] = f(s.theta + dt * k3t, s.omega + dt * k3o);
  s.theta += (dt / 6) * (k1t + 2 * k2t + 2 * k3t + k4t);
  s.omega += (dt / 6) * (k1o + 2 * k2o + 2 * k3o + k4o);
}

// Run it
const state = { theta: 1, omega: 0 }; // released from rest at 1 rad (~57°)
for (let t = 0; t < 100; t += 0.02) semiImplicitEuler(state, 0.02);
console.log(energy(state));

How much energy does each method lose or gain?

A frictionless pendulum must conserve energy, so drift in EE is a direct measure of numerical error. We released the bob from 11 rad on a 11 m string and ran 100100 s (about 50 swings):

MethodΔt = 0.02 sΔt = 0.005 s
Explicit Euler+2,175% (blows up)+566%
Semi-implicit Eulerwobbles within ±3%wobbles within ±0.7%
RK40.0003%0.0000003%

Explicit Euler pushes the bob slightly further out on every swing, so the amplitude keeps growing. Semi-implicit Euler is symplectic: the energy error oscillates around the true value instead of drifting away, which is why it is the default in most game and physics engines. RK4 is dramatically more accurate per step, but it does not have that structural guarantee, so its error still creeps upward over very long runs.

Choosing a time step
For an oscillator with period TT, keep Δt\Delta t below about T/100T/100 with the Euler variants (RK4 tolerates larger). Cutting Δt\Delta t by four cut the semi-implicit wobble by about four in the table above.

What PhysicsHub does

  • The Simple Pendulum simulation does not integrate an angle at all: the bob is a free body under gravity and the string is a Distance constraint to the pivot, stepped with semi-implicit Euler at a fixed 1/120 s.
  • The Double Pendulum integrates the exact Lagrangian equations for the two angles with rk4, because chaos amplifies any error and a constraint solver on free masses would not be accurate enough.
Chaos changes what "correct" means
In a chaotic system any numerical error grows exponentially, so a single trajectory becomes meaningless after the Lyapunov time. Judge such simulations by their statistics — the shape of the attractor — not by matching one exact path.

Frequently asked questions

Why does explicit Euler make a pendulum gain energy?

It advances the position using the old velocity and the velocity using the old position, so each step overshoots the true curve slightly outward. Those small outward errors add up every step and the amplitude grows without limit.

What is a symplectic integrator?

One that preserves the geometric structure of Hamiltonian mechanics. In practice, the energy error oscillates around the true value instead of drifting, which keeps long simulations of orbits and oscillators stable. Semi-implicit Euler and Störmer–Verlet are the common examples.

When should I use RK4 instead of semi-implicit Euler?

When you need high accuracy over short-to-medium runs and can afford four force evaluations per step — for example the double pendulum. For real-time simulations with many bodies and long runs, a symplectic method at a small step is usually the better trade.

How small should the time step be?

Small enough that the period is covered by at least 50–100 steps for Euler-type methods. If the energy of a frictionless system visibly drifts or wobbles, halve the step and check again.

Keep exploring