5.4.23Scientific Computing (Python)

Implementing ODE solvers from scratch — Euler, RK4

1,907 words9 min readdifficulty · medium

WHAT problem are we solving?

WHY discretize? Most real f(t,y)f(t,y) have no closed-form integral. But the slope ff is always computable. So we walk forward in tiny straight-line hops.


Euler's Method — deriving from first principles

HOW do we get from yny_n to yn+1y_{n+1}? Use the definition of a derivative: y(tn)=limh0y(tn+h)y(tn)hyn+1ynhy'(t_n) = \lim_{h\to 0}\frac{y(t_n+h)-y(t_n)}{h} \approx \frac{y_{n+1}-y_n}{h}

Drop the limit (use a finite hh) and solve for yn+1y_{n+1}:

Equivalently from a Taylor expansion: y(tn+h)=y(tn)+hy(tn)+h22y(ξ)error we throw awayy(t_n+h) = y(t_n) + h\,y'(t_n) + \underbrace{\tfrac{h^2}{2}y''(\xi)}_{\text{error we throw away}} The discarded term is O(h2)O(h^2) per steplocal truncation error O(h2)O(h^2). Over N=T/hN = T/h steps the errors accumulate to global error ==O(h)====O(h)==. Halve hh → halve the error. That's slow.

def euler(f, t0, y0, h, n):
    t, y = t0, y0
    ts, ys = [t], [y]
    for _ in range(n):
        y = y + h * f(t, y)   # one slope, whole step
        t = t + h
        ts.append(t); ys.append(y)
    return ts, ys

RK4 — averaging four slopes

WHY do better? Euler uses the slope only at the left of the interval, so it consistently over/undershoots when the curve bends. RK4 samples the slope at the start, the middle (twice), and the end, then takes a weighted average — analogous to Simpson's rule for the integral tntn+hfdt\int_{t_n}^{t_n+h} f\,dt.

Why the weights 1,2,2,11,2,2,1? Sum =6= 6, so h6()\frac h6(\dots) is a true weighted mean slope. RK4 uses two separate midpoint slopes (k2,k3k_2, k_3), each given weight 22, because the midpoint best represents the average behaviour over [tn,tn+h][t_n, t_n+h]. This is analogous to Simpson's 1/31/3 rule (which weights endpoint–midpoint–endpoint as 1,4,11,4,1): both put extra weight on the middle of the interval. RK4 splits Simpson's single "44" into two midpoint evaluations k2,k3k_2,k_3 that together carry weight 2+2=42+2=4. Matching the Taylor series up to h4h^4 forces exactly these coefficients.

  • Local truncation error O(h5)O(h^5), global error ==O(h4)====O(h^4)==.
  • Halve hh → error drops by 24=16×2^4 = 16\times. That's why RK4 is the workhorse.
def rk4(f, t0, y0, h, n):
    t, y = t0, y0
    ts, ys = [t], [y]
    for _ in range(n):
        k1 = f(t,         y)
        k2 = f(t + h/2,   y + h/2 * k1)
        k3 = f(t + h/2,   y + h/2 * k2)
        k4 = f(t + h,     y + h   * k3)
        y = y + (h/6) * (k1 + 2*k2 + 2*k3 + k4)
        t = t + h
        ts.append(t); ys.append(y)
    return ts, ys
Figure — Implementing ODE solvers from scratch — Euler, RK4

Worked Example 1 — y=yy' = y, y(0)=1y(0)=1 (true: ete^t)

Take h=1h = 1, one step, find y1y_1.

Euler: y1=y0+hf(t0,y0)=1+11=2y_1 = y_0 + h f(t_0,y_0) = 1 + 1\cdot 1 = 2. Why? One left-slope step. True value e12.718e^1 \approx 2.718 → error 0.7180.718. Big!

RK4:

  • k1=f(0,1)=1k_1 = f(0,1)=1why? slope = yy = 1.
  • k2=f(0.5,1+0.51)=1.5k_2 = f(0.5,\,1+0.5\cdot1)=1.5why? nudge yy by half-step using k1k_1.
  • k3=f(0.5,1+0.51.5)=1.75k_3 = f(0.5,\,1+0.5\cdot1.5)=1.75why? refine midpoint using k2k_2.
  • k4=f(1,1+11.75)=2.75k_4 = f(1,\,1+1\cdot1.75)=2.75why? end slope using k3k_3.
  • y1=1+16(1+3+3.5+2.75)=1+10.2562.7083y_1 = 1 + \frac16(1 + 3 + 3.5 + 2.75) = 1 + \frac{10.25}{6} \approx 2.7083.

Error 0.0099\approx 0.009970× better than Euler with the same step size.


Worked Example 2 — error scaling check (y=yy'=y, integrate to t=1t=1)

Method h=0.1h=0.1 error h=0.05h=0.05 error ratio
Euler 0.125\approx 0.125 0.065\approx 0.065 2\approx 2 (matches O(h)O(h))
RK4 2.1×106\approx 2.1\times10^{-6} 1.3×107\approx 1.3\times10^{-7} 16\approx 16 (matches O(h4)O(h^4))

Why this matters: halving hh helps Euler twice but helps RK4 sixteen times — the entire reason RK4 dominates practical computing.



Recall Feynman: explain to a 12-year-old

Imagine walking in fog where a tiny compass tells you which way to step right where you stand. Euler just trusts that one reading and walks a full step — but if the path curves, you drift off. RK4 is smarter: you peek ahead to the middle, peek again, peek at the far end, then take the average of all those compass readings before stepping. Averaging four peeks keeps you almost perfectly on the path.


Flashcards

What ODE form do Euler and RK4 solve?
An IVP: y=f(t,y)y'=f(t,y) with y(t0)=y0y(t_0)=y_0, by stepping forward at spacing hh.
Write the forward Euler update.
yn+1=yn+hf(tn,yn)y_{n+1}=y_n+h\,f(t_n,y_n).
Where does Euler get its slope?
Only at the left endpoint (tn,yn)(t_n,y_n), assumed constant over the step.
Euler's global error order?
O(h)O(h) (local truncation O(h2)O(h^2)).
Write the four RK4 stages.
k1=f(t,y)k_1=f(t,y); k2=f(t+h2,y+h2k1)k_2=f(t+\tfrac h2,y+\tfrac h2 k_1); k3=f(t+h2,y+h2k2)k_3=f(t+\tfrac h2,y+\tfrac h2 k_2); k4=f(t+h,y+hk3)k_4=f(t+h,y+h k_3).
RK4 final update formula?
yn+1=yn+h6(k1+2k2+2k3+k4)y_{n+1}=y_n+\frac h6(k_1+2k_2+2k_3+k_4).
Why weights 1,2,2,1?
Weighted mean (sum 6) of slopes; the two midpoint slopes count double each (total 4) — analogous to Simpson's rule's middle weight; forced by matching Taylor series to h4h^4.
Are RK4 weights identical to Simpson's (1,4,1)(1,4,1)?
No — analogous, not identical. RK4 uses (1,2,2,1)(1,2,2,1) with two midpoint evaluations whose weights sum to 4.
RK4 global error order?
O(h4)O(h^4) — halving hh cuts error ~16×.
Each RK4 stage builds on which previous stage?
k2k_2 uses k1k_1, k3k_3 uses k2k_2, k4k_4 uses k3k_3 — sequential, not all from k1k_1.
Why is RK4 cheaper than Euler at equal accuracy?
Euler cost ~1/ε1/\varepsilon, RK4 ~1/ε1/41/\varepsilon^{1/4}; four ff-calls per step buy huge accuracy.

Connections

  • Taylor Series Expansion — both methods derived by truncating it.
  • Simpson's Rule — RK4 weights are analogous to it.
  • Finite Difference Approximation of Derivatives — Euler is forward difference.
  • Numerical Stability and Stiff ODEs — why explicit methods can blow up.
  • Adaptive Step Size (RK45 / Dormand–Prince) — practical extension of RK4.
  • scipy.integrate.solve_ivp — library version of what we built.

Concept Map

slope given by

approximate at

no closed form so

derivative definition

Taylor expansion

one slope whole step

accumulates over N steps

slow so improve

samples 4 slopes

weighted mean 1,2,2,1

analogous to

Initial Value Problem

f t,y

Discrete points step h

Forward Euler

Local error O h^2

Global error O h

Classical RK4

k1 k2 k3 k4

y_n+1 update

Simpson 1/3 rule

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Dekho, ODE ka matlab hai ki tumhe har point pe sirf slope pata hai: y=f(t,y)y' = f(t,y). Tumhe poora curve nahi pata, bas yeh pata hai ki kis direction me badhna hai. To numerical solving ka funda simple hai — known point se start karo, slope dekho, chhota sa step (hh) lo, aur repeat karte raho. Yahi fog me chalne jaisa hai jahan ek compass har jagah direction batata hai.

Euler sabse seedha tareeka hai: bas left point ka ek slope leke poora step maar do — yn+1=yn+hf(tn,yn)y_{n+1} = y_n + h f(t_n,y_n). Problem yeh hai ki agar curve mud raha hai to tum drift kar jaoge, kyunki ek hi slope par bharosa kar liya. Iska error O(h)O(h) hai, yani hh aadha karo to error sirf aadha hota hai — bahut slow.

RK4 smart hai: yeh ek nahi, chaar slopes leta hai — start (k1k_1), do baar midpoint (k2,k3k_2, k_3), aur end (k4k_4) — phir weighted average h6(k1+2k2+2k3+k4)\frac{h}{6}(k_1+2k_2+2k_3+k_4) leta hai. Weights 1,2,2,11,2,2,1 Simpson's rule jaise analogous hain (Simpson ke weights 1,4,11,4,1 hote hain), kyunki RK4 do midpoint evaluations karta hai jinka total weight 2+2=42+2=4 ho jaata hai — Simpson ke beech wale 44 ke barabar. Lekin yeh bilkul same nahi hai. Iska error O(h4)O(h^4)hh aadha karo to error 16 guna kam! Isiliye real-world computing me RK4 default choice hai.

Important baat: har RK4 stage pichle stage pe banta hai (k3k_3 me k2k_2 use hota hai, k1k_1 nahi), aur agar ff me tt aata hai to tt ko bhi shift karna mat bhoolna. Bas yeh do galtiyaan avoid karo, baaki RK4 magic hai.

Go deeper — visual, from zero

Test yourself — Scientific Computing (Python)

Connections