Lesson 4 of 15

RK4 Integration

RK4 Integration

Just as with Euler's method, we can chain multiple RK4 steps together to integrate over an interval.

Algorithm

def rk4(f, t0, y0, t_end, n):
    h = (t_end - t0) / n
    t, y = t0, y0
    ys = [y0]
    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 += h
        ys.append(y)
    return ys

RK4 vs Euler: A Comparison

For dydt=y\frac{dy}{dt} = y, y(0)=1y(0) = 1, approximate y(1)=e2.71828y(1) = e \approx 2.71828:

Methodn=10n=100
Euler2.59372.7048
RK42.71832.71828

With just 10 steps, RK4 matches ee to 4 decimal places. Euler needs thousands of steps for similar accuracy.

Your Task

Implement rk4(f, t0, y0, t_end, n) that applies nn RK4 steps and returns a list of n+1n+1 values.

Pyodide loading...
Loading...
Click "Run" to execute your code.