5.4.23 · D2Scientific Computing (Python)

Visual walkthrough — Implementing ODE solvers from scratch — Euler, RK4

2,740 words12 min readBack to topic

Everything here deepens the parent note: the parent topic.


Step 1 — What an ODE actually hands you

WHAT. We do not know the curve . We only own the machine that reports the slope at any point we choose to stand.

WHY. For most real problems there is no formula for — but is always a thing you can compute (it's just arithmetic). So the game is: turn "I know the slope everywhere" into "I know the curve."

PICTURE. Below, the faint dashed curve is the true (which the solver cannot see). At one point we place a short arrow — that arrow is what tells us: the direction to walk right here.

Figure — Implementing ODE solvers from scratch — Euler, RK4
  • ::: the machine that returns the slope at any point you stand on.
  • What smoothness does RK4 need? ::: smooth enough that has a valid Taylor expansion through the term (roughly 4 continuous derivatives).

Step 2 — Laying down the grid, then turning a slope into a step

WHAT. We refuse to take all the way to zero. We keep it small but finite and read the equation backwards to solve for the next rung.

WHY this tool. We want to predict one rung ahead, and the derivative definition is the only bridge between "slope now" and "value a bit later." Dropping the limit is the single approximation that starts everything.

HOW — the algebra, one move at a time. Start from the finite- version and drop the limit: Multiply both sides by (clears the fraction): Add to both sides (isolates the unknown ):

PICTURE. The right triangle below makes rise-over-run literal: run along the bottom, rise up the side. Follow the slope line and you land at .

Figure — Implementing ODE solvers from scratch — Euler, RK4
  • ::: the step size — the horizontal gap between grid rungs and .
  • ::: our current best estimate of at time .
  • How are the discrete times defined? ::: , so .

Step 3 — Euler's method: trust one slope, take the whole hop

WHAT. We measure the slope once, at the start of the interval, and walk in that straight line for the entire step .

WHY it's shaky. The true curve bends during the step. But Euler froze the slope at the left edge, so if the curve is concave up, Euler's straight line falls below the truth; concave down, it overshoots above. The error is baked in the moment we commit to a single slope.

PICTURE. Watch the red Euler segment leave the true curve tangentially and then drift away as the curve bends up under it. The vertical gap at is the local error of this one step.

Figure — Implementing ODE solvers from scratch — Euler, RK4

Step 4 — The RK4 idea: don't guess, peek ahead

WHAT. We will collect four slope samples before committing to a single averaged hop.

WHY four, and why the middle twice. Expand the true step as a Taylor series in : the exact answer is . Each slope sample , itself Taylor-expanded, contributes its own pieces. The weights over are the unique mixture that makes the pieces of the blend match the true series term-for-term; the first mismatch is at . The two midpoint samples carry the bulk of the and corrections — the same instinct as Simpson's Rule, which also loads weight on the midpoint.

PICTURE. Left panel: four slope arrows on the interval (start , midpoint , end ). Right panel: a skeletal "ledger" showing each power of and how the weighted blend cancels the true-series term at that power, leaving the first leftover at .

Figure — Implementing ODE solvers from scratch — Euler, RK4
  • Which power of is the first RK4 does not match? ::: — everything through is cancelled exactly.

Step 5 — Building and (start, then first midpoint peek)

WHAT. is our first honest reading. uses merely to scout the midpoint, then measures a fresh slope at that scouted spot.

WHY. The midpoint slope corrects for the curve's bending that alone missed. We must move to the midpoint (in both and ) before reading, otherwise we'd just get again.

PICTURE. The dashed blue trial-line is the half-step driven by ; the solid arrow at its tip is , visibly steeper because the curve is climbing.

Figure — Implementing ODE solvers from scratch — Euler, RK4
  • ::: slope at the left edge, the same slope Euler uses.
  • ::: slope at the midpoint reached by a trial half-step along .

Step 6 — Refining with and reaching the end with

WHAT. is a second, improved midpoint estimate; is the end-of-interval estimate built on .

WHY the chain . Each stage stands on the previous one so that errors partially cancel when averaged. This sequential dependence is the whole trick.

PICTURE. Two midpoint arrows ( pale-yellow, pink) sit almost on top of each other but the pink is nudged closer to truth; the far-right arrow is .

Figure — Implementing ODE solvers from scratch — Euler, RK4

Step 7 — The weighted average: one hop worth four peeks

WHAT. We collapse four readings into one averaged slope and take a single Euler-style hop with it.

WHY . The midpoint best represents the interval's average behaviour, so it earns double weight — echoing how Simpson's Rule loads its middle sample. These exact numbers are the only choice that makes the update agree with the true Taylor series through the term (Step 4).

PICTURE. The green averaged slope (blended from the four arrows) drives one clean hop that lands essentially on the true curve — compare the tiny green gap to Step 3's fat red gap.

Figure — Implementing ODE solvers from scratch — Euler, RK4

Step 8 — Edge & degenerate cases (so nothing surprises you)

WHAT. We check the boundaries: an that ignores , an that ignores , a nearly-flat step, and a backward step.

  • Autonomous only (no ): the and shifts still exist but do nothing, since ignores . RK4 still works; the shifts are simply harmless — the figure below shows the two midpoint samples landing at the same slope value because only matters.
  • Pure-time only (no , e.g. ): now every inside the stages is ignored, and RK4 collapses exactly into Simpson's rule for . Here the two midpoint samples become identical — they fuse into Simpson's single midpoint with combined weight . This is the clearest proof of the RK4–Simpson kinship.
  • Flat step, : all four 's are , so . Both methods correctly refuse to move. No division blows up because we divide by the constant , never by .
  • Backward step, : every formula is unchanged; and simply move left. Useful for reversing an integration.

WHY show these. If you only ever test a bending curve you might forget that forgetting the -shifts silently works for autonomous and breaks for non-autonomous .

PICTURE (autonomous). Left: depends on only, so at both midpoint times the slope read is the same height-driven value — the -shift changes nothing.

Figure — Implementing ODE solvers from scratch — Euler, RK4

PICTURE (pure-time → Simpson). Here : the four slope readings land at ; the two midpoint reads coincide and the shaded area under is what RK4 computes — literally Simpson's rule.

Figure — Implementing ODE solvers from scratch — Euler, RK4

The one-picture summary

WHAT. One figure, both methods, same start, same : Euler's red straight hop drifting off, RK4's four peeks blending into a green hop that hugs the true curve. Watch the two error gaps at .

Figure — Implementing ODE solvers from scratch — Euler, RK4
Recall Feynman: the whole walkthrough in plain words

You're crossing a valley in fog. You mark equally spaced checkpoints ahead — that's the grid . All you have is a compass that, wherever you stand, tells you which way the ground tilts — that's . Euler reads the tilt once at your feet and marches a full step in that direction. But the valley curves, so you drift off the trail; take smaller steps and you drift less, but you'll be walking forever. RK4 is patient: it reads the tilt at your feet (), scouts half a step ahead and reads it there (), scouts the midpoint again using that better reading (), then scouts the far end (). It blends the four readings — counting the two middle ones double, dividing by six — into one trustworthy direction, and takes a single step along that. Four careful peeks per step keep you almost perfectly on the trail, which is why serious computing leans on RK4. (Walking backward? Just make negative — every formula still holds.)


Connections

  • Taylor Series Expansion — the weights are forced by matching this series to .
  • Simpson's Rule — Step 8's pure-time case shows RK4 literally becoming Simpson.
  • Finite Difference Approximation of Derivatives — Step 2's dropped limit is the forward difference.
  • Numerical Stability and Stiff ODEs — what happens when even RK4's small step isn't safe.
  • Adaptive Step Size (RK45 / Dormand–Prince) — let the solver choose from the error it senses.
  • scipy.integrate.solve_ivp — the production tool that wraps all of this.