Solve an initial-value problem dy/dx = f(x, y) with y(x₀) = y₀ using classical RK4. Type any expression in x and y (supports sin, cos, exp, log, sqrt, abs, pow, plus the constants pi and e). Compare against Euler and Heun (RK2), and provide an optional exact solution to visualize the error.
| n | xₙ | yₙ | k₁ | k₂ | k₃ | k₄ | Δy | y Euler | y Heun | exact | |err RK4| |
|---|
Given dy/dx = f(x, y) and a step size h, RK4 takes four slope samples per step:
k₁ = f(xₙ, yₙ),
k₂ = f(xₙ + h/2, yₙ + h·k₁/2),
k₃ = f(xₙ + h/2, yₙ + h·k₂/2),
k₄ = f(xₙ + h, yₙ + h·k₃),
then combines them with a weighted average
yₙ₊₁ = yₙ + h·(k₁ + 2k₂ + 2k₃ + k₄)/6.
Local truncation error is O(h⁵) and global error is O(h⁴) — halving the step size cuts the error by roughly sixteen. It's the workhorse of physics simulations and numerical libraries for that reason, provided the problem isn't stiff (widely separated timescales, where an implicit method wins).