Task 3 of 6
Euler's mistake is committing. It reads the slope at the start of the step and then pretends that slope holds all the way across. The midpoint method (RK2) makes the obvious repair: take a trial half-step, read the slope there, throw the trial away, and take the real full step using that better slope.
Two force evaluations per step instead of one, and the error goes from first order to
second: halve dt and the error drops by four.
Same instrument as the last task; only the number at the bottom changes.
The step sizes are coarser here — 25 to 200 steps, not 50 to 400 — and that is worth knowing rather than glossing. A convergence study only reads true inside a window. Too coarse and the leading error term is not yet dominant; too fine and the error sinks into the rounding noise of the float32 the WebGL backend computes in, and the ratio starts reporting arithmetic instead of mathematics.
midX = x + v·(dt/2) and midV = v + a·(dt/2), with a = −xx += midV·dt and v += (−midX)·dtNothing about midX and midV survives the step. They
exist only to answer one question — what is the slope halfway across? — and
the answer is midV for the position and −midX for the
velocity.
The state is (x, v) and its derivative is
(v, −x). So the midpoint velocity drives the position, and the
midpoint position drives the velocity. Crossing those over is the single
easiest way to get this wrong.
const half = dt / 2;
const a = -x;
const midX = x + v * half;
const midV = v + a * half;
x = x + midV * dt;
v = v + -midX * dt;This page is an interactive exercise — the editor, the GPU runner and your saved progress need JavaScript. The text above is the full brief.