Lesson 10 of 15

Runge-Kutta Method

Runge-Kutta 4th Order Method

The Runge-Kutta 4th order method (RK4) is the workhorse numerical integrator for ordinary differential equations dy/dx=f(x,y)dy/dx = f(x, y). It achieves O(h4)O(h^4) global accuracy by sampling the slope at four points per step.

RK4 Algorithm

Given the current state (xn,yn)(x_n, y_n) and step size hh:

k1=hf(xn,yn)k_1 = h\, f(x_n,\, y_n) k2=hf ⁣(xn+h2,yn+k12)k_2 = h\, f\!\left(x_n + \tfrac{h}{2},\, y_n + \tfrac{k_1}{2}\right) k3=hf ⁣(xn+h2,yn+k22)k_3 = h\, f\!\left(x_n + \tfrac{h}{2},\, y_n + \tfrac{k_2}{2}\right) k4=hf(xn+h,yn+k3)k_4 = h\, f(x_n + h,\, y_n + k_3)

yn+1=yn+k1+2k2+2k3+k46y_{n+1} = y_n + \frac{k_1 + 2k_2 + 2k_3 + k_4}{6}

The weighted average gives RK4 its 4th-order accuracy: inner slopes are counted twice.

Harmonic Oscillator System

The harmonic oscillator y¨+ω2y=0\ddot{y} + \omega^2 y = 0 can be rewritten as a system of two first-order ODEs:

dydt=v,dvdt=ω2y\frac{dy}{dt} = v, \qquad \frac{dv}{dt} = -\omega^2 y

RK4 is applied to both equations simultaneously at each step. With initial conditions y(0)=1y(0) = 1, v(0)=0v(0) = 0, the exact solution is y(t)=cos(ωt)y(t) = \cos(\omega t).

Accuracy vs. Step Size

Step size hhGlobal error for dy/dx=ydy/dx = y
0.1107\sim 10^{-7}
0.011011\sim 10^{-11}

Your Task

Implement rk4_step(f, x, y, h) that advances the solution by one step and returns the new yy value. Implement rk4_solve(f, x0, y0, x_end, h) that returns a list of (x, y) tuples for the full solution. Implement harmonic_oscillator_rk4(omega, t_end, y0=1.0, v0=0.0, h=0.01) that solves the harmonic oscillator system and returns (t_values, y_values) as lists.

Python runtime loading...
Loading...
Click "Run" to execute your code.