Task 3 of 6

Look Before You Leap

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.

the trial half-step is thrown away; only the slope it found is kept
Goal: replace the Euler step with a midpoint step, and watch the ratio go from 2 to 4.

Requirements

Hint 1 — what the trial step is for

Nothing 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.

Hint 2 — which slope goes where

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.

Hint 3 — the whole step
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;

Same idea elsewhere

A multi-stage integrator has to hold several copies of the state at once, and on a GPU that is register pressure — the resource that decides how many threads a streaming multiprocessor can keep in flight. CUDA calls it occupancy, WebGPU and Metal have the same constraint under different names. It is a real reason production codes sometimes prefer a cheap scheme with a smaller step to an elegant one with a bigger footprint.

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.