Integrating an ODE with RK4
Advance a differential equation using the classic fourth-order Runge-Kutta method and see why its error shrinks as the step to the fourth power.
The method
For y' = f(t,y), RK4 takes four slope samples per step and combines them: k1 at the start, k2 and k3 at the midpoint, k4 at the end, then y_new = y + (dt/6)(k1 + 2k2 + 2k3 + k4). It is fourth-order: halving dt cuts error by sixteen.
The four stages
- k1 = f(t, y)
- k2 = f(t + dt/2, y + dt k1/2)
- k3 = f(t + dt/2, y + dt k2/2)
- k4 = f(t + dt, y + dt k3)
Worked case
Solve y' = -y with y(0) = 1; the exact solution is exp(-t). RK4 tracks it to high accuracy even with modest steps.
import numpy as np
def rk4(f,y,t,dt):
k1=f(t,y); k2=f(t+dt/2,y+dt*k1/2)
k3=f(t+dt/2,y+dt*k2/2); k4=f(t+dt,y+dt*k3)
return y+dt/6*(k1+2*k2+2*k3+k4)
f=lambda t,y:-y; y=1.0; dt=0.1
for n in range(10): y=rk4(f,y,n*dt,dt)
print(round(y,6), round(np.exp(-1),6)) # 0.367879 vs 0.367879
Why four samples
RK4 matches the Taylor expansion of the true solution through the fourth-order term, cancelling the leading error a single Euler step would carry. It hits a sweet spot: much more accurate than Euler for little extra work, without the bookkeeping of adaptive or implicit methods.
Limits
RK4 is explicit, so stiff systems still force tiny steps for stability. For those, implicit methods or stiff solvers are needed. But for smooth, non-stiff problems RK4 remains the default workhorse.