Numerical methods

Euler to Runge-Kutta

The one-step methods for y′=f(t,y)y' = f(t, y) and a two-step method, run in doubles with their table of steps. The validated solver supplies the true solution at every step, so the global error is in the table, and halving the step shows each method's order.

const r = odeMethod("y - t^2 + 1", { y0: "1/2", until: 2, steps: 10, method: "rk4" });
r.steps;        // [{ n, t, y, exact, error }, …]
r.finalError;   // the true error at t = 2

stepSizeStudy("y - t^2 + 1", { y0: "1/2", until: 2, method: "euler" }).rows;
// [{ steps, h, error, ratio, observedOrder }, …]

stability("rk4").interval;   // [-2.785…, 0]

The methods

methodstep from (t,y)(t, y) with size hhorder
eulery+h f(t,y)y + h\,f(t, y)1
heuny+h2 (k1+f(t+h, y+hk1))y + \tfrac h2\,(k_1 + f(t + h,\ y + h k_1)), k1=f(t,y)k_1 = f(t, y)2
midpointy+h f(t+h2, y+h2k1)y + h\,f(t + \tfrac h2,\ y + \tfrac h2 k_1)2
rk4y+h6 (k1+2k2+2k3+k4)y + \tfrac h6\,(k_1 + 2k_2 + 2k_3 + k_4), the classical four stages4
ab2y+h2 (3fn−fn−1)y + \tfrac h2\,(3f_n - f_{n-1}), Adams-Bashforth, started with one Heun step2

Local and global error

A method of order pp makes an error of size hp+1h^{p+1} in one step (the local error). Over the 1/h1/h steps needed to cross a fixed interval these add up, and the global error at the end is of size hph^p. So halving hh divides the final error by about 2p2^p: by 2 for Euler, by 16 for the classical Runge-Kutta method. stepSizeStudy runs the same problem with several step counts and reports the ratio of successive errors and the order it implies.

The errors are true ones: at each step the method's double is compared with the validated enclosure of y(tn)y(t_n), and error is the largest possible distance between them.

Stability

On the test equation y′=λyy' = \lambda y each of these methods multiplies yy by a polynomial R(hλ)R(h\lambda) per step: 1+z1 + z for Euler, 1+z+12z21 + z + \tfrac12 z^2 for the second-order methods, and the degree-4 Taylor polynomial of eze^z for rk4. The true solution decays when λ<0\lambda < 0; the numerical one decays only when ∣R(hλ)∣<1|R(h\lambda)| < 1. For real negative zz that is an interval, (−2,0)(-2, 0) for Euler and (−2.785…,0)(-2.785\ldots, 0) for rk4, with the left end enclosed here as a root of R(z)=1R(z) = 1. A step size outside it makes the computed solution grow although the true one dies away: the reason stiff equations force small steps on explicit methods.

callreturns
odeMethod(f, { y0, t0 = 0, until, steps = 10, method }){ method, order, h, steps: [{ n, t, y, exact, error }], finalError }
stepSizeStudy(f, { …, counts }){ rows: [{ steps, h, error, ratio, observedOrder }] }
stability(method){ polynomial, interval, largestStep(lambda) }
Try itEdit the code and run it with @ratmath/analytic and Core's R, Rational, RationalInterval in scope. The last line's value is shown; PRINT(…) adds lines, TEX(…) typesets math.
Ctrl/⌘ + Enter runs