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 , , approximate :
| Method | n=10 | n=100 |
|---|---|---|
| Euler | 2.5937 | 2.7048 |
| RK4 | 2.7183 | 2.71828 |
With just 10 steps, RK4 matches to 4 decimal places. Euler needs thousands of steps for similar accuracy.
Your Task
Implement rk4(f, t0, y0, t_end, n) that applies RK4 steps and returns a list of values.
Pyodide loading...
Loading...
Click "Run" to execute your code.