Task 4 of 6

Four Slopes, Weighted

Classical RK4 samples the slope four times per step — once at the start, twice at the middle (the second one using the first one's estimate), once at the end — and combines them (k₁ + 2·k₂ + 2·k₃ + k₄) / 6. Four evaluations, fourth order: halving dt divides the error by sixteen.

Which is why this task's step sizes look absurd. The coarsest level crosses t = 0…5 in five steps — a full radian each — and it is still more accurate than 400 Euler steps. Run RK4 at Euler's finest setting instead and its error would be around 10⁻⁹, roughly a thousand times below what float32 can resolve next to a value of order 1; the study would measure rounding, not convergence. Three levels is what fits between "not yet asymptotic" and "already noise" — take one more halving and the ratio stops being a clean 16.

Goal: write the RK4 step and watch the ratio jump to ≈16.

Requirements

Hint 1 — the derivative of the state

The state is (x, v), so every slope is a pair: the derivative of x is v, and the derivative of v is −x. That gives k1x = v and k1v = −x, and every later probe is the same rule evaluated at a shifted state.

Hint 2 — the middle two

k2 is the slope half a step along k1; k3 is the slope half a step along k2:

const k2x = v + k1v * half;
const k2v = -(x + k1x * half);
const k3x = v + k2v * half;
const k3v = -(x + k2x * half);

Building k3 from k1 again is the classic slip, and it costs you two whole orders.

Hint 3 — the combination
x = x + (dt / 6) * (k1x + 2 * k2x + 2 * k3x + k4x);
v = v + (dt / 6) * (k1v + 2 * k2v + 2 * k3v + k4v);

The middle pair carries twice the weight, and the six is what the weights sum to.

Same idea elsewhere

RK4 trades memory traffic for arithmetic: four evaluations of the derivative per step, all of them on values already sitting in registers. That is exactly the bargain GPUs reward — arithmetic is nearly free, and the force evaluation in a real simulation is usually memory-bound, so fewer, bigger, better steps often beat more cheap ones. It is the same arithmetic-intensity argument that drives kernel fusion in CUDA, WebGPU and Metal.

All tasks in ODE Integrators

  1. One Thread, One Whole Trajectory
  2. Halve the Step, Halve the Error
  3. Look Before You Leap
  4. Four Slopes, Weighted
  5. Velocity Verlet: the Symplectic Step
  6. Payoff: RK4 Drifts, Verlet Does Not

This page is an interactive exercise — the editor, the GPU runner and your saved progress need JavaScript. The text above is the full brief.