Skip to content

Documentation / @interstellar-tools/equations / rk4Integrate

Function: rk4Integrate() ​

ts
function rk4Integrate(
  f: OdeRightHandSideType,
  y0: readonly number[],
  t0: number,
  t1: number,
  steps: number,
  options?: {
    every?: number;
    stop?: (t: number, y: readonly number[]) => boolean;
  }
): OdeSolutionInterface;

Defined in: helpers/rk4.ts:115

Integrate a system of ODEs from t0 to t1 in fixed fourth-order Runge–Kutta steps.

Takes steps steps of h=(t1−t0)/steps with rk4Step, and returns the state after each, starting with y0 at t0.

Notes

  • stop(t, y), if given, is checked after every step; when it returns true the integration ends there, and the last sample is the state that triggered it. Use it to catch a crash into a body, or a crossing.
  • every keeps only every n-th sample (the last one is always kept), to save memory on long runs.
  • t1 may be before t0, to integrate backwards.

Parameters ​

ParameterTypeDescription
fOdeRightHandSideTypeThe right-hand side f(t,y).
y0readonly number[]State at t0 (finite components).
t0numberStart time (finite).
t1numberEnd time (finite, not equal to t0).
stepsnumberNumber of steps (integer, >= 1).
options?{ every?: number; stop?: (t: number, y: readonly number[]) => boolean; }stop, a function that ends the integration early, and every, the sampling interval (integer, >= 1; default 1).
options.every?number-
options.stop?(t: number, y: readonly number[]) => boolean-

Returns ​

OdeSolutionInterface

The times and states, t[k] with y[k].

Throws ​

  • If a number is not finite, or steps or every is not an integer.
  • If t1 = t0, steps < 1 or every < 1.

Example ​

ts
// A harmonic oscillator over one period: back where it started
const { y } = rk4Integrate(
  (_t, [x, v]) => [v, -x],
  [1, 0],
  0,
  2 * Math.PI,
  1000
);
y[y.length - 1]; // ≈ [1, 0]

See ​

rk4Step