Runge-Kutta Method
Runge-Kutta 4th Order Method
The Runge-Kutta 4th order method (RK4) is the workhorse numerical integrator for ordinary differential equations . It achieves global accuracy by sampling the slope at four points per step.
RK4 Algorithm
Given the current state and step size :
The weighted average gives RK4 its 4th-order accuracy: inner slopes are counted twice.
Harmonic Oscillator System
The harmonic oscillator can be rewritten as a system of two first-order ODEs:
RK4 is applied to both equations simultaneously at each step. With initial conditions , , the exact solution is .
Accuracy vs. Step Size
| Step size | Global error for |
|---|---|
| 0.1 | |
| 0.01 |
Your Task
Implement rk4_step(f, x, y, h) that advances the solution by one step and returns the new 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.