Lesson 3 of 15

Runge-Kutta 4 (RK4)

Runge-Kutta 4th Order

Euler's method uses only the slope at the start of each step. The Runge-Kutta 4 method (RK4) samples the slope at four points within the step and takes a weighted average — achieving fourth-order accuracy.

The Formula

k1=f(t,  y)k_1 = f(t,\; y) k2=f ⁣(t+h2,  y+h2k1)k_2 = f\!\left(t + \tfrac{h}{2},\; y + \tfrac{h}{2} k_1\right) k3=f ⁣(t+h2,  y+h2k2)k_3 = f\!\left(t + \tfrac{h}{2},\; y + \tfrac{h}{2} k_2\right) k4=f(t+h,  y+hk3)k_4 = f(t + h,\; y + h\, k_3)

ynext=y+h6(k1+2k2+2k3+k4)y_{\text{next}} = y + \frac{h}{6}\left(k_1 + 2k_2 + 2k_3 + k_4\right)

  • k1k_1: slope at the start
  • k2k_2: slope at the midpoint using k1k_1
  • k3k_3: slope at the midpoint using k2k_2 (refined)
  • k4k_4: slope at the end using k3k_3

The weights (1,2,2,1)(1, 2, 2, 1) follow Simpson's rule for numerical integration.

Why RK4?

With the same step size, RK4 is dramatically more accurate than Euler. For dydt=y\frac{dy}{dt} = y with h=0.1h = 0.1:

  • Euler: error ~0.005 per step
  • RK4: error ~0.000000002 per step

RK4 is the workhorse of scientific computing. It is used in physics simulations, orbital mechanics, and engineering systems everywhere Euler is too inaccurate.

Your Task

Implement rk4_step(f, t, y, h) that returns the next y value using one RK4 step.

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