5.4.23 · D3Scientific Computing (Python)

Worked examples — Implementing ODE solvers from scratch — Euler, RK4

3,211 words15 min readBack to topic

You already met Euler and RK4 in the parent note. This page does one thing: it drags those two update rules through every kind of situation a step-marching solver can face — growth, decay, oscillation, a curve that bends the "wrong" way, a step so big the method blows up, a real-world cooling problem, and an exam trap. If you can follow all of these, no ODE-solver question can surprise you.

Before we start, let me re-anchor the two tools in plain words so nothing below uses a symbol you haven't been handed.

The word "slope" is the hero of every example. Keep this picture in your head: a hiker in fog reading a compass at their feet (Euler) versus a hiker who peeks ahead three times before committing (RK4).


The scenario matrix

Every case class an ODE-stepper can be asked about, and the example that hits it:

Cell What makes it distinct Example
A. Growth slope grows, curve bends up → Euler undershoots Ex 1
B. Decay slope shrinks, curve bends toward zero → sign of error flips Ex 2
C. Non-autonomous slope depends on — the -shifts inside matter Ex 3
D. Oscillation curve turns both ways; slope passes through zero Ex 4
E. Degenerate / zero slope flat line; both methods must return a constant Ex 5
F. Big-step instability large on decay both methods blow up past a critical Ex 6
G. Real-world word problem Newton cooling, must set up and read units Ex 7
H. Exam twist reuse- trap + error-scaling reasoning Ex 8

We work all eight below. Each one asks you to Forecast first — actually guess before reading the steps.


Example 1 — Cell A: exponential growth ,

Forecast: the curve bends upward (slope keeps increasing). Euler reads the slope only at the low-left start, so it uses too-small a slope → it should undershoot. Which method lands closer? Guess now.

  1. Euler. . Why this step? Euler assumes the starting slope holds for the whole half-step. Since the real slope rises during the step, falls short of .
  2. RK4 . . Why? Slope right where we stand — the same reading Euler used.
  3. RK4 . . Why? Peek at the midpoint , nudging forward with . The slope there is bigger — this already corrects the undershoot.
  4. RK4 . . Why? Re-do the midpoint but nudge with the better slope . Each stage refines the last.
  5. RK4 . . Why? The end-of-step slope, using to get there.
  6. RK4 combine. . Why the ? Weighted mean slope; midpoints count double because they best represent the average over the step. Note the inner sum: … wait — count carefully: .

Let me state the arithmetic cleanly so nothing is fudged: the weighted sum is so

Verify: true . Euler error ; RK4 error — RK4 is ~530× closer on a single step. Undershoot forecast confirmed for Euler. ✓

Read the figure: in Figure s01 the white curve is the true . Follow the amber line — it is Euler's straight hop, and it ends below the white curve: that gap is the undershoot you forecast. The cyan square is RK4's endpoint, sitting practically on the white curve. The visual takeaway: one straight Euler segment cannot hug a bending curve, but RK4's four-slope average can.

Figure — Implementing ODE solvers from scratch — Euler, RK4

Example 2 — Cell B: exponential decay ,

Forecast: now the curve bends toward zero from above — it is convex, flattening as it drops. Euler uses the steep starting slope for the whole step. Will it land above or below the true value?

  1. Euler. . Why this step? The starting slope is the steepest descent the curve ever has here; using it for the whole step drops us too far.
  2. Compare. True , so Euler at undershoots (lands below). Why note this? In Cell A (growth) Euler landed below the curve too, but there "below" meant "too small a rise". Here "below" means "dropped too fast". The lesson: Euler always errs on the side of the starting slope, and whether that's high or low depends on curvature — but for both growth and this decay it lands under the true curve because both are convex.

Verify: actual error. The leading-order Taylor estimate is — the right order of magnitude; higher-order terms in the expansion account for the gap up to the true . ✓


Example 3 — Cell C: non-autonomous ,

Forecast: here ignores entirely — the slope is set purely by time. This is exactly the case where forgetting the -shifts inside silently ruins you. Guess: will RK4 be exact or approximate for a parabola?

Throughout this example the step size is , so wherever you see it means and means — I keep in the formulas and substitute at the end so the general shape stays visible.

  1. . . Why? Slope at the very start, , is zero.
  2. . . Why? We must evaluate at , not . The -nudge is irrelevant because doesn't read , but the -shift is everything.
  3. . . Why? Same → same slope . Confirms the two midpoint slopes agree when is -independent.
  4. . . Why? End-of-step slope at .
  5. Combine. Keeping the factor explicit: Why? Weighted average of the four slopes, scaled by since , lands exactly.

Verify: true at is → RK4 error . Why exact? RK4 matches the Taylor series through ; a quadratic has no terms beyond , so RK4 is exact for it. ✓


Example 4 — Cell D: oscillation ,

Forecast: the slope starts at (rising fast) but decreases to by the end of this quarter-period. Euler locks in the biggest slope of the interval. Overshoot or undershoot?

  1. Euler. . Why this step? Euler trusts the start slope across the whole quarter-turn. But the real slope keeps shrinking to zero, so a constant slope of overshoots badly.
  2. Interpret. True value , Euler gives overshoot of . Why the flip from Ex 1? In growth the missed slope was larger later (undershoot). Here the missed slope is smaller later, so the same "trust-the-start" rule now overshoots. This is why curvature sign, not method, decides the direction of error.

Verify: . Overshoot confirmed. ✓

Read the figure: in Figure s02 the white curve is rising to then flattening. The amber straight line is Euler's step — it climbs at the constant steep slope and shoots above the white curve, ending at while the true endpoint (cyan square) sits at . Contrast this with s01: same "trust the start slope" rule, but here the curve flattens so the error points the opposite way. That sign-flip is the whole lesson.

Figure — Implementing ODE solvers from scratch — Euler, RK4

Example 5 — Cell E: degenerate zero slope ,

Forecast: slope is zero everywhere. A correct solver must return unchanged. If yours drifts, it's buggy.

  1. Euler. . Why? Zero slope × any step = no movement.
  2. RK4. , so . Why? Every peek reads zero; the weighted average of zeros is zero.

Verify: both return exactly for any . ✓ This is the cheapest but most important unit test — run it first on any solver you write.


Example 6 — Cell F: big-step instability ,

First, a symbol we need. When an ODE has the form , the number (Greek "lambda") is just the growth/decay coefficient — the same role played by in the matrix's rows "" and "". For our problem we simply read off (a decay, because it is negative). Everything below is written with so the rule is reusable, but for us .

Forecast: the true solution decays monotonically toward zero. But watch what a big step does. Guess: will Euler's numbers stay small and positive?

  1. Step 1. . Why the disaster? Euler multiplies the step by the slope . With the correction overshoots past zero into negative territory — physically impossible for a decay.
  2. Step 2. . Why? The overshoot flips the sign, the slope flips too, and the error grows each step.
  3. Step 3. . Why? Each step the magnitude multiplies by . It doubles forever — unstable.

Euler's stability rule: forward Euler on stays bounded only if . Here , so we need . Our violates it.

Does RK4 escape? No — higher order does not mean unconditionally stable. For each RK4 step multiplies by the polynomial (the Taylor series of truncated at — exactly the four stages). RK4 is bounded only if . With we get and whose magnitude , so RK4 with also blows up on this problem. RK4's stability limit here is roughly (where ) — larger than Euler's , but still finite. The lesson: for stiff decay you must shrink for both methods; see Numerical Stability and Stiff ODEs.

Verify: with the safe : Euler — still negative but , so magnitudes now shrink, not grow. Sequence . Bounded. For RK4 at , gives , , so RK4 is bounded too. ✓

Read the figure: in Figure s03 the white curve is the true decay hugging zero. The amber zig-zag is Euler with : it flings above and below the white dashed zero-line, each swing bigger than the last — that is the doubling you computed. The cyan markers are Euler with the safe : same alternating signs but each swing smaller, spiralling into zero. The picture makes "unstable vs bounded" a matter of whether the zig-zag grows or shrinks.

Figure — Implementing ODE solvers from scratch — Euler, RK4

Example 7 — Cell G: real-world word problem (Newton's cooling)

Forecast: the cup cools fast at first (big gap → steep slope), then slowly. Over a whole 10-minute step, Euler will use only the initial steep slope. Overshoot or undershoot the true temperature?

Set up: . Units: . Start .

  1. Euler. slope . . Why suspicious? Euler predicts the coffee reaches room temperature exactly, using the fast initial cooling for all 10 minutes. Real cooling slows down, so it can't cool that much.
  2. RK4 . .
  3. RK4 . -nudge: ; . Why? midpoint slope is gentler because the cup already cooled.
  4. RK4 . ; . Why? refine the midpoint with .
  5. RK4 . ; . Why? end slope, gentlest of all.
  6. Combine. The weighted sum of slopes is . So .

Verify: exact solution , so . Euler's is a gross overshoot in cooling (off by ); RK4's is off by only despite one giant 10-minute step. ✓ Units all in . Forecast (Euler cools too much) confirmed.


Example 8 — Cell H: exam twist (the reuse- trap + scaling)

Forecast (a): reusing makes and identical — the method loses an independent slope. Will be too big or too small versus the correct ?

Part (a):

  1. Correct stages (from parent): , giving correct .
  2. Buggy . (same as ). Why the damage? no longer refines ; the two midpoint peeks now carry identical information, so the averaging is weaker.
  3. Buggy . . Why changed? builds on the wrong .
  4. Combine. . Why worse? True ; correct RK4 gave (error ), buggy gives (error ) — the bug is ~ worse, collapsing toward Euler-like quality.

Part (b):

  1. Scaling law. RK4 error . Going from to is a factor reduction in step. Why ? Global error order is (parent), so error shrinks by .
  2. Predict. .

Verify: (a) buggy inner sum , so ; its gap from the correct RK4 value is . ✓ (b) . ✓

Recall Which cell taught which lesson?

Growth vs decay :::: curvature sign, not the method, decides over/undershoot direction (Ex 1, 2, 4). Non-autonomous :::: never skip the -shift inside (Ex 3). Zero slope :::: both methods must return a constant for any — your first unit test (Ex 5). Big step :::: Euler is bounded only if ; RK4 is bounded only if — both have a finite limit (Ex 6). Reuse- :::: each stage must feed the next or you drop back toward first order (Ex 8a).


Connections

  • Taylor Series Expansion — why RK4 is exact on the quadratic in Ex 3, and the source of the error in Ex 2.
  • Simpson's Rule — the averaging philosophy behind Ex 1's RK4 step.
  • Finite Difference Approximation of Derivatives — the forward difference that is Euler.
  • Numerical Stability and Stiff ODEs — the blow-up in Ex 6 explained in full.
  • Adaptive Step Size (RK45 / Dormand–Prince) — how solvers pick so Ex 6 never happens.
  • scipy.integrate.solve_ivp — the production tool that wraps all of this.