Skip to content

Documentation / @interstellar-tools/equations / rk4Step

Function: rk4Step() ​

ts
function rk4Step(
  f: OdeRightHandSideType,
  t: number,
  y: readonly number[],
  h: number
): number[];

Defined in: helpers/rk4.ts:42

Take one fourth-order Runge–Kutta step of a system of ODEs, y˙=f(t,y).

yn+1=yn+h6(k1+2k2+2k3+k4)

with k1=f(t,y), k2=f(t+h/2,y+hk1/2), k3=f(t+h/2,y+hk2/2) and k4=f(t+h,y+hk3).

Notes

  • The error per step shrinks as h5, and over a fixed interval as h4: halving the step makes the result about 16 times more accurate.
  • A fixed step suits smooth problems. Close passes, where the forces change quickly, need a step small enough for the closest one.
  • h may be negative, to integrate backwards.

Parameters ​

ParameterTypeDescription
fOdeRightHandSideTypeThe right-hand side f(t,y), returning an array as long as y.
tnumberTime t at the start of the step (finite).
yreadonly number[]State y at t (finite components).
hnumberStep size h (finite, non-zero).

Returns ​

number[]

The state at t + h.

Throws ​

  • If t, h or a component of y is not finite, or f returns an array of the wrong length.
  • If h is zero.

Example ​

ts
// dy/dt = y from y = 1: one step of 0.1 gives e^0.1 to 7 digits
rk4Step((_t, [y]) => [y], 0, [1], 0.1); // [1.1051708...]

See ​