Task 4 of 6
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.
k1 at the start, k2 and k3 at the midpoint, k4 at the endk2 and k3 step out by dt/2; k4 by the full dtk3 from k2, k4 from k31, 2, 2, 1 over 6The 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.
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.
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.
This page is an interactive exercise — the editor, the GPU runner and your saved progress need JavaScript. The text above is the full brief.