Learn/Numerics/Differential Equations

Differential Equations

Integrate ordinary differential equations from a script: non-stiff and stiff solvers, their options and results, and how to choose between them.

Time33 min readLevelIntermediateUpdatedUpdated Nov 2026
Script language

01Overview

What an ODE Solver Does

An ordinary differential equation gives the rate of change of a state, and a solver steps that state forward in time. A battery temperature, a pendulum angle and a tank level are all states that an ODE can describe.

The library solves initial-value problems: the rate of change as a function of time and state, a starting state, and a span of time. It chooses its own step sizes to hold the error below a tolerance you set. It offers two non-stiff solvers (ode45 and ode23) and three stiff solvers (ode15s, ode23s and ode_radau). In the Rust crate and in Rune each of the five can also locate events.

Luau reaches all five solvers, each with an options form: ten names in the Numerics table. Rune reaches five more names, which take events and a Jacobian and return an OdeSolution with dense output; choose Rune at the top of the page to read them. Rune reaches all five solvers, each with an options form: ten names in the eustress::realism::numerics module, and five more, ode45_events, ode23_events, ode15s_events, ode23s_events and ode_radau_events, which take events and a Jacobian and return an OdeSolution with dense output; that is fifteen names in Rune. Luau has no event functions, no Jacobian argument and no dense output. The Rust crate eustress-numerics has all of them; the sections below say which language reaches each feature. The conventions shared by every routine (the Numerics tableeustress::realism::numerics module, matrices, results and errors) are on the Numerics overview.

Writing the Problem

Every solver takes the same three pieces. The right-hand side is a function of the time and the state vector that gives the derivative of each state variable. The initial state is a finite, non-empty vector. The time span is a start and an end, both finite; the end may be earlier than the start, and the solver then integrates backward. A span of zero length returns the initial point and nothing else.

The right-hand side must return finite values at the initial point. If it does not, the solver stops before the first step with the error invalid argument: ode: the derivative is not finite at the initial point.

In a script the right-hand side is a function of the time and the state array that returns the derivative as an array with one value per state. The state is a table, indexed from 1: function(t, y) return {-y[1]} end. The state is an array, indexed from 0: |t, y| [-y[0]]. A returned array of the wrong length fails the call with a message that names the number of values returned and the number of states.

The initial state is an array of numbers. The time span is an array of exactly two numbers, [t0, t1]; any other count fails with tspan must be two numbers [t0, t1] followed by the count it got. To read the solution at chosen times, use the requested-times option described under Output at Requested Times.

The smallest complete example solves y' = -y from y(0) = 1 over the span 0 to 1, at rtol 1e-9 and atol 1e-12, and reads the last state. The exact answer is exp(-1), about 0.3679, and a test in each language asserts that the result lies within 1e-8 of it.

Luau
local sol = Numerics.ode45(function(t, y) return {-y[1]} end, {0, 1}, {1}, {rtol = 1e-9, atol = 1e-12})
print(string.format("%.4f", sol.y[#sol.y][1]))   -- 0.3679
Rune
use eustress::log_info;
use eustress::realism::numerics;

pub fn on_init() {
    let sol = numerics::ode45_with(|t, y| [-y[0]], [0.0, 1.0], [1.0], #{rtol: 1e-9, atol: 1e-12})?;
    let ys = sol["y"];
    let n = ys.len();
    let last = ys[n - 1][0];
    log_info(`y(1) = ${last}`);   // 0.3679 to four decimals
}

The Five Solvers

SolverMethodUse it for
ode45Dormand-Prince 5(4) pair, with a free 4th-order interpolantNon-stiff problems; the default
ode23Bogacki-Shampine 3(2) pairNon-stiff problems, at lower order
ode15sVariable-order (1 to 5) numerical differentiation formulas, quasi-constant stepStiff problems at moderate tolerances
ode23sModified Rosenbrock (2, 3) pair of Shampine and ReicheltStiff problems at crude tolerances
ode_radauThree-stage Radau IIA method of order 5, after Hairer and Wanner's RADAU5Stiff problems at tight tolerances

MATLAB has no solver of the ode_radau class. The crate covers the options in full: relative and absolute tolerance, largest step, first step, and the Jacobian. A script sets the tolerances, the largest step, the first step, the step budget and the requested output times; Rune also passes a Jacobian and turns on dense output through the *_events solvers; Luau passes no Jacobian and has no dense output. The absolute tolerance is a single number that applies to every state variable; per-variable absolute tolerances, non-negativity constraints, output functions and the refine option are not available.

The five solvers take the same arguments and return the same result in both languages. Luau has optional arguments, so the options table goes last and each _with name is the same function as its base name. Rune has no optional arguments, so the base form takes three arguments and the _with form takes the options object as a fourth.

FormLuau
DefaultsNumerics.ode45(f, tspan, y0)
With optionsNumerics.ode45(f, tspan, y0, opts) or Numerics.ode45_with(f, tspan, y0, opts)
Other solversReplace ode45 with ode23, ode15s, ode23s or ode_radau; the argument order is the same.
With events (Rune only)Not reachable
FormRune
Defaultsnumerics::ode45(f, tspan, y0)?
With optionsnumerics::ode45_with(f, tspan, y0, opts)?
Other solversReplace ode45 with ode23, ode15s, ode23s or ode_radau; the argument order is the same.
With events (Rune only)numerics::ode45_events(f, tspan, y0, opts, events)?

02Non-Stiff Solvers

The Default Solver

ode45 uses the Dormand-Prince 5(4) pair: a fifth-order step with a fourth-order estimate of the error. It is the solver to try first. Each attempted step costs six evaluations of the right-hand side, and the first evaluation of a step reuses the last one of the previous step.

ode45 and ode23 control the step size as follows; the stiff solvers have their own controllers, described below. The error of a step is measured in the RMS norm, scaled by the absolute tolerance plus the relative tolerance times the larger of the old and new state magnitudes. A step is accepted when that error is within tolerance. The next step size is the current one times 0.9 times the error raised to the power -1/(q+1), limited to the range 0.2 to 10, where q is the order of the error estimate (4 for ode45, 2 for ode23). Right after a rejected step the size does not grow.

The test suite checks ode45 against SciPy:

ProblemReferenceSettingsError bound the test enforces
Van der Pol, mu = 1, y(0) = (2, 0), t from 0 to 20, 41 output timesSciPy DOP853 at rtol and atol 1e-13rtol 1e-10, atol 1e-12Below 2e-8, relative to the largest reference value
The same problemThe same referencertol 1e-4, 1e-6 and 1e-8 (atol is rtol times 0.01)Below 2e-2, 2e-4 and 2e-6; each tighter tolerance must give a smaller error
Lorenz (sigma 10, rho 28, beta 8/3), y(0) = (1, 1, 1), t from 0 to 5SciPy DOP853 at rtol and atol 1e-13rtol 1e-8, atol 1e-10Below 2e-6, and within 3 times the error SciPy RK45 shows at the same tolerance
y' = -y integrated backward from t = 1 to t = 0The exact value 1rtol 1e-9, atol 1e-12Relative error below 1e-8

A further test checks the step controller itself: the default tolerance finishes the Van der Pol problem in fewer than 120 accepted steps while rejecting some steps, and tightening to rtol 1e-9 takes more than 8 times as many. The step counts per solver for the larger problems are on the Performance page.

From a script, ode45 takes the right-hand side, the span and the initial state, and an optional options tablethe ode45_with form for options. It returns the solution as a tablean object with these fields:

  • t: the output times, an array.
  • y: one array of states per output time, so y[k] is the state at t[k] and is read by row. sol.y[k][j] is state j at output time k, counting from 1.sol["y"][k][j] is state j at output time k, counting from 0.
  • nfev, accepted and rejected: the number of right-hand side evaluations, accepted steps and rejected steps.

A failure is an ordinary script error. Catch it with pcall; the error text begins with runtime error: Numerics.ode45: and ends with a stack traceback, and an error your own right-hand side raises comes back carrying its own message. The call returns Err with a string that starts with numerics::ode45:, and ? turns it into a script error; an error raised inside your closure comes back as numerics::ode45: the callback failed: followed by its message. When the solver itself fails, the text after that prefix starts with no convergence: or invalid argument:, which is the kind. After the first error from your function the solver does not call it again.

The Lower-Order Solver

ode23 uses the Bogacki-Shampine 3(2) pair: a third-order step with a second-order error estimate. It follows the same step control and takes the same options and the same result as ode45.

The test suite solves the Van der Pol problem above (mu = 1, t from 0 to 20) with ode23 at rtol 1e-7 and atol 1e-9 and requires an error below 2e-5 against the SciPy DOP853 reference.

In a script, ode23 has the same arguments, options and result as ode45: Numerics.ode23(f, tspan, y0)numerics::ode23(f, tspan, y0)? and numerics::ode23_with(f, tspan, y0, opts)?.

Output at Requested Times

By default a solver returns one output point per accepted step, plus the initial point. Two options change that.

  • Requested times: a list of output times. The solver returns the state at exactly those times, computed from the interpolant of the step that contains each one. The times must lie inside the span and must be strictly monotone in the direction of integration; otherwise the call fails with ode: t_eval must lie inside tspan or ode: t_eval must be strictly monotone in the direction of integration.
  • Dense output: an option that keeps the interpolant of every step, so the solution can be evaluated at any time inside the span after the solve. Asking for a time outside the span fails with OdeSolution::eval: time outside the integration range, and asking without the option fails with OdeSolution::eval: solve with OdeOptions::dense = true first.

The test suite checks dense output on y' = -y + sin t, y(0) = 1, which has a closed form. At rtol 1e-9 and atol 1e-12, ode45 evaluated at 1001 points from 0 to 10 stays within 5e-8 of the closed form. ode15s at rtol 1e-8 and atol 1e-10, evaluated at 201 points, stays within 5e-6.

A solution carries these pieces:

PieceMeaning
tThe output times
the statesOne state vector per output time; the library reads one with y(i), one variable's history with component(j), and any time with eval(t)
eventsThe events located, in time order (see below)
terminatedTrue when a terminal event stopped the run before the end of the span
statsWork counters: nfev (right-hand side evaluations, finite-difference Jacobian evaluations included), nfev_jac (the part of nfev spent on finite-difference Jacobians, zero when you supply the Jacobian), njev (Jacobian evaluations), nlu (LU factorizations), accepted and rejected (steps)

The five base solvers return t, y, nfev, accepted and rejected, spelled that way in both languages. The states are read by row: y[k] is the whole state vector at t[k]. Those solvers do not return the counters nfev_jac, njev and nlu, have no events or terminated piece and give no dense output, because their result is plain arrays. The *_events solvers return an OdeSolution that carries every piece in the table, with eval(t) and component(j) as methods.Luau has no result that carries every piece in the table.

To read the solution at times you choose, pass the t_eval option, an array of numbers that obeys the rules above. Write it as {t_eval = {0, 0.5, 1}}. Write it through the _with form as #{t_eval: [0.0, 0.5, 1.0]}. The result's t array then holds exactly those times.

03Stiff Problems

What Stiff Means

A problem is stiff when it holds a very fast mode and a slow one together: an explicit solver must take steps as small as the fast mode needs even after that mode has died away.

Two stiff problems appear in the test suite. The first is the Van der Pol oscillator with mu = 1000, y' = (y2, 1000 (1 - y1^2) y2 - y1), starting from (2, 0) and run to t = 3000. The second is the Robertson chemical kinetics problem, run from (1, 0, 0) to t = 4000:

  • y1' = -0.04 y1 + 10000 y2 y3
  • y2' = 0.04 y1 - 10000 y2 y3 - 30000000 y2^2
  • y3' = 30000000 y2^2

The coefficients in the Robertson problem range from 0.04 to 30000000: a fast mode and a slow one in the same system.

0500100015002000250030001e-71e-61e-51e-40.0010.010.1110100step size (log scale)time tode45: every 84th of its 1,689,290 accepted stepsode15s: all 1,495 accepted steps
Step size against time for y1 prime = y2, y2 prime = 1000 (1 - y1 squared) y2 - y1, from (2, 0) to t = 3000, both solvers at rtol 1e-6 and atol 1e-8. The vertical axis is logarithmic. Drawn from ode_vdp_step_sizes.csv, real output of the library. The ode45 trace shows every 84th of its 1,689,290 accepted steps (the run also rejected 281,475); ode15s took 1,495 accepted steps (134 rejected) and every one is drawn. The step sizes ran from 8.3e-5 to 3.2e-2 for ode45 and from 1.5e-7 to 52.5 for ode15s. Each trace is thinned to at most 200 points with the peaks kept. These counts describe two solvers on one stiff problem; they are not a comparison with another library.

The figure comes from one run of each solver on the Van der Pol problem with mu = 1000 at rtol 1e-6 and atol 1e-8. ode45 took 1,689,290 accepted steps and rejected 281,475; its steps never exceeded 0.032, and it made 11,824,592 evaluations of the right-hand side. ode15s took 1,495 accepted steps and rejected 134, with step sizes from 1.5e-7 up to 52.5, and made 3,261 evaluations. The two runs end at nearly the same state: y1 is -1.51060 for ode45 and -1.51052 for ode15s. These counts describe the two solvers on one stiff problem; the Performance page has the other measured runs.

The Stiff Solvers

ode15s follows the quasi-constant-step numerical differentiation scheme of Shampine and Reichelt, with orders 1 to 5 and a simplified Newton iteration. Its corrector is solved to a tenth of the error tolerance. It is the stiff solver for moderate tolerances. It refuses an rtol below 1000 times machine epsilon (about 2.2e-13), and at rtol 1e-10 on the stiff Van der Pol problem it runs out of digits and fails; the next subsection has the numbers.

ode23s is a one-step modified Rosenbrock (2, 3) method. It suits crude tolerances; for tight ones, use ode15s, or ode_radau for the tightest.

The test suite checks both against SciPy Radau references. The same suite checks ode_radau in the next subsection.

ProblemSolver and settingsError bound the test enforces
Van der Pol, mu = 1000, 8 output times from 100 to 3000ode15s, rtol 1e-6, atol 1e-8Below 5e-4 relative error in y1 at every output time, and an error at the last time within 3 times the SciPy BDF error at the same tolerance
The sameode15s with the analytic Jacobian, rtol 1e-8, atol 1e-10Below 2e-5
The sameode23s, rtol 1e-5, atol 1e-8Below 5e-3
Robertson, 5 output times from 0.4 to 4000ode15s, rtol 1e-7, atol 1e-11Below 2e-4 in every component
The sameode23s, rtol 1e-5, atol 1e-10Below 2e-3 in every component; the three components still sum to 1 within 1e-6

In a script, ode15s and ode23s have the same arguments, options and result as ode45, with the same call form: Numerics.ode15s(f, tspan, y0)numerics::ode15s_with(f, tspan, y0, opts)?. Luau cannot pass a Jacobian, so both solvers estimate it by finite differences.Rune passes a Jacobian through ode15s_events and ode23s_events, described under Supplying the Jacobian.

Tight Tolerances: ode_radau

ode_radau is the three-stage Radau IIA method of order 5, after Hairer and Wanner's RADAU5 and SciPy's Radau. Each step runs a simplified Newton iteration on the transformed stage system, with one real and one complex LU factorization per step size, reused while the step is kept. The error estimate is the embedded third-order one, filtered through the real LU, and the step control is predictive. The collocation polynomial of each step gives dense output and the starting values for the next step. It is the solver for stiff problems at tolerances tighter than about 1e-8, where the backward-difference formulas of ode15s need many more steps or run out of digits.

It takes the same options and defaults as the other four solvers (rtol 1e-3, atol 1e-6, automatic first step, no step ceiling, 10 million attempted steps), the same Jacobian argument with forward differences when you give none, and the same event handling. Its failure messages carry the prefix ode_radau:.

The test suite checks ode_radau against SciPy Radau at rtol 1e-4, 1e-6, 1e-8 and 1e-10. It requires an error of at most 1.1 times SciPy's on the Van der Pol problem with mu = 1000 and at most 1.25 times on Robertson, and a number of right-hand side evaluations of at most 1.02 times SciPy's, counted without the finite-difference Jacobian calls that SciPy leaves out. The three components of the Robertson solution still sum to 1 within 1e-9. Further checks: fixed steps of 0.5 and 0.25 show an observed order between 4.6 and 5.6 on y' = -y + sin t; dense output stays within 2e-7 of the closed form at rtol 1e-9; backward integration and the falling-ball event agree to 1e-8; a blow-up and bad input are errors; and at rtol 1e-10 on the Van der Pol problem the end value agrees with the reference to 1e-9.

Error and evaluations against SciPy Radau, in the library's own measured run (the error is the largest relative error against a reference computed at 1e-11 or tighter; evaluations exclude finite-difference Jacobian calls):

ProblemrtolError, ode_radauError, SciPy RadauEvaluations, ode_radauEvaluations, SciPy Radau
Van der Pol, mu = 1000, t to 30001e-41.39e-51.39e-538563883
The same1e-61.25e-71.34e-799209920
The same1e-88.41e-108.79e-102981629951
The same1e-101.27e-111.27e-118850187898
Robertson, t to 40001e-46.04e-66.15e-6514514
The same1e-67.50e-81.36e-714211421
The same1e-81.12e-91.21e-941844180
The same1e-101.40e-111.27e-111263612669

ode_radau matches SciPy's Radau. SciPy is slightly ahead in three places: the Robertson error at rtol 1e-10 (1.40e-11 against 1.27e-11, a factor of 1.10), the Van der Pol evaluations at rtol 1e-10 (88501 against 87898, 0.7 percent more), and the Robertson evaluations at rtol 1e-8 (4184 against 4180, 0.1 percent more). Everywhere else ode_radau is level or ahead; at Robertson with rtol 1e-6 its error is 1.8 times smaller.

ode15s on the same Van der Pol problem (mu = 1000, t to 3000), error against the same reference:

rtolode15sSciPy BDFSciPy LSODASciPy Radau
1e-43.61e-32.59e-34.79e-31.39e-5
1e-66.02e-57.50e-58.08e-51.34e-7
1e-81.49e-61.03e-68.27e-78.78e-10

ode15s is less accurate than SciPy's BDF at rtol 1e-4, less accurate than BDF and LSODA at rtol 1e-8, and less accurate than SciPy's Radau at every tolerance in the table. It is more accurate than BDF and LSODA at rtol 1e-6. At rtol 1e-10 it fails: the run ends with a step size underflow, and the message names ode_radau. At rtol 1e-14 it refuses the call. Use ode_radau for those tolerances.

From a script, ode_radau has the same arguments, options and result as ode15s: Numerics.ode_radau(f, tspan, y0, opts)numerics::ode_radau_with(f, tspan, y0, opts)?. Without a Jacobian it estimates one by finite differences; Luau cannot supply one; Rune can supply one through ode_radau_events.

Supplying the Jacobian

All three stiff solvers use the Jacobian df/dy. In the Rust crate you pass a function that fills an n-by-n matrix with the partial derivatives at a given time and state, or pass nothing and the solver estimates the Jacobian by forward differences. Each estimated Jacobian costs n extra evaluations of the right-hand side, and the count appears in the evaluation counter.

The Van der Pol case above is tested both ways. With the analytic Jacobian, whose first row is 0 and 1 and whose second row is -2000 y1 y2 - 1 and 1000 (1 - y1^2), ode15s agrees with the reference.

Luau cannot pass a Jacobian: the stiff solvers it calls estimate it by finite differences, which costs n extra evaluations of your right-hand side per Jacobian.

Rune passes a Jacobian as the jacobian option of ode15s_events, ode23s_events or ode_radau_events: a function |t, y| J that returns the n by n matrix of partial derivatives as an array of rows. ode45_events and ode23_events reject the option with an error that names the three stiff forms. With a supplied Jacobian the counter nfev_jac stays at 0 and njev counts the calls; a function that returns a matrix of the wrong size fails the call. The second example under Events in Rune, below, solves a stiff problem this way.

Choosing a Solver

Your systemdy/dt = f(t, y)ode45the defaultode23lower orderexplicit pairsode15sorder 1 to 5, moderate tolerancesode23sone step, crude tolerancesode_radauorder 5, tight tolerancesuse the Jacobian
Start with ode45. For a stiff problem use ode15s at moderate tolerances and ode_radau at tolerances tighter than about 1e-8; ode23s is the one-step alternative for crude tolerances.
  • Start with ode45. It is the default, and for a problem that is not stiff it is the one to use.
  • ode23 is the lower-order non-stiff solver, a 3(2) pair against ode45's 5(4).
  • Move to a stiff solver when an explicit solver fails with no convergence: ode: step size underflow at t = 0.99...; the problem may be stiff or singular or needs a very large number of steps.
  • ode15s is the general stiff solver at moderate tolerances. Its accuracy is below SciPy's BDF, LSODA and Radau in some of the cases above, and it fails at rtol 1e-10 on the stiff Van der Pol problem.
  • ode23s is the one-step stiff solver for crude tolerances.
  • ode_radau is the stiff solver for tight tolerances, below about 1e-8. It matches SciPy's Radau.

More measured runs of the stiff solvers are on the Performance page.

04Events

Finding When Something Happens

An event is a condition the solution crosses, such as a ball reaching the floor. The solver locates the crossing time and can stop there.

Each event is a function of time and state that returns one number; the event happens where that number crosses zero. Each event also has two settings:

  • Terminal: when true, the integration stops at the event. When false, the solver records the event and continues.
  • Direction: 0 reports any crossing, +1 only a crossing from negative to non-negative, and -1 only a crossing from positive to non-positive.

You can watch several events in one solve. The solution lists the events it located in time order. Each entry holds the index of the event in your list, the time of the crossing and the state at the crossing. The solution's terminated flag is true when a terminal event ended the run early, and the last output point is then the event point.

The solver checks the sign of each event function at the end of every accepted step. Where the sign changed, it finds the crossing time by Brent root finding on the step's interpolant, to a tolerance of 4 times machine epsilon times the larger time. A function that crosses zero and crosses back inside one step shows no sign change at the step ends and is not located.

Rune passes event functions to the *_events solvers, described in the next subsection.

Luau has no event functions: the solvers it calls take no event argument, so a Luau script cannot stop a solve at a crossing and cannot read a located crossing time. A Luau script that wants to know when a quantity crossed zero can read the returned arrays: the crossing lies between the first two output points where the quantity changes sign. That gives an interval and not the crossing time to solver tolerance, and a quantity that crosses and crosses back between two output points is missed.

Example: A Falling Ball

The library's test events_locate_the_bounce_and_stop drops a ball from 10 m with zero starting velocity under gravity 9.81 m/s^2, with a span of 0 to 10 s, rtol 1e-8 and atol 1e-10. The state is height and velocity. It watches two events: the height reaching 0 (terminal, falling only) and the height passing 5 m (not terminal, either direction).

The test checks that the run stops at the ground event and reports two events in time order, the 5 m crossing first. The closed-form times are the square root of 2h/g: for the crossing at 5 m, h is the 5 m dropped; for the landing, h is 10 m. Both located times agree with the closed form to a relative error of 1e-9, the height at the landing is below 1e-8 in magnitude, and the last output time equals the landing time.

Two more checks in the same test. A rising-only watch on the ground, run for 2 s, never fires, so the solution has no events and is not terminated. ode15s, given the same falling-only ground event, locates the landing time to a relative error of 1e-6.

0510height (m)event: t = 1.427843 sexact sqrt(2h/g) = 1.427843 s00.250.50.7511.251.5-15-10-50velocity (m/s)time (s)velocity at the event: -14.007 m/s (red dot)
The falling ball of the events example, from ode_falling_ball.csv, real output of the library: y(0) = (10 m, 0), g = 9.81, rtol 1e-8, atol 1e-10, output requested every 0.01 s up to 1.4 s. The red line is the terminal ground event, located at t = 1.427843 s, the same to seven decimals as the exact value sqrt(2h/g). At the event the height is -3.2e-14 m and the velocity is -14.007 m/s. Top: height. Bottom: velocity.

In the library run, ode45 located the ground event at t = 1.427843123 s, which matches the exact value of the square root of 2h/g to all the digits printed. The state at the event is a height of -3.2e-14 m and a velocity of -14.007 m/s. The run ends at the event, and the last output point is the event point.

The test runs through the Rust crate. The Rune subsection below shows the landing event through ode45_events.Luau has no version of the landing event.

Events, Jacobians and Dense Output in Rune

Luau does not reach the event solvers, Jacobian option and dense output described here. Choose Rune at the top of the page to read this part.

Rune reaches events, a user Jacobian and dense output through five solvers: ode45_events, ode23_events, ode15s_events, ode23s_events and ode_radau_events. Luau does not reach them. All five take the same five arguments, in this order:

  1. f: the right-hand side, |t, y| [..], as for the base solvers.
  2. tspan: the array [t0, t1].
  3. y0: the initial state array.
  4. opts: an options object. It is required; pass #{} for the defaults.
  5. events: an array of events, which may be empty.

Each entry of the events array is either a function |t, y| value or an object with the fields g, terminal and direction. A bare function is an event that is not terminal and reports a crossing in either direction.

  • g: the event function |t, y| value, which returns one number. The event happens where it crosses zero. Required in the object form.
  • terminal: true or false; false when absent. True stops the integration at the event.
  • direction: -1, 0 or 1; 0 when absent. 0 reports any crossing, 1 a crossing from negative to non-negative, -1 a crossing from positive to non-positive. Any other number fails the call.

A field other than these three is an error that lists the three names, and an object without g is an error.

The options object takes rtol, atol, max_step, first_step, max_steps and t_eval as the base solvers do, plus dense (true or false) and, for ode15s_events, ode23s_events and ode_radau_events only, jacobian. The jacobian option is a function |t, y| J that returns the n by n matrix of df/dy as an array of rows. Passing it to ode45_events or ode23_events fails with numerics::ode45_events: option jacobian is for the stiff solvers (ode15s_events, ode23s_events, ode_radau_events), with the solver's own name in place of ode45_events. An unknown option name is an error that lists the valid names.

The result is an OdeSolution. It has no constructor; only the five solvers return one. Its fields are read with a dot:

  • t and y: the output times and the states, one array per output time, as in the base solvers.
  • events: an array of located events in time order, each an object with index (the position of the event in your array, from 0), t (the crossing time) and y (the state at the crossing).
  • terminated: true when a terminal event stopped the run before the end of the span.
  • nfev, nfev_jac, njev, nlu, accepted and rejected: the work counters described under Output at Requested Times.

Its methods are:

  • sol.eval(t): the state array at time t. It needs the option dense: true; without it the call fails with an error that ends in solve with the option dense: true first.
  • sol.component(j): the time history of state j, counting from 0, as an array. A state that does not exist is an error.
  • sol.y_last(): the state array at the last output time.
  • sol.len(): the number of output times.
  • sol.dim(): the number of states.

Methods that can fail, eval and component, return a result that ? unwraps; the others return their value directly.

Rune Examples

The examples here use the event solvers, which Luau does not reach. Choose Rune at the top of the page to read them.

The first example is the falling ball. The state is height and velocity, the ball starts at 10 m with zero velocity under gravity 9.81 m/s^2, and the single event is the height reaching zero, terminal and falling only. The run stops at the landing, so terminated is true, one event is recorded, and its time equals the square root of 2 times 10 divided by 9.81. The test that backs this example checks the time against that closed form to 1e-8.

Rune
use eustress::log_info;
use eustress::realism::numerics;

pub fn on_init() {
    let ground = #{g: |t, y| y[0], terminal: true, direction: -1};
    let sol = numerics::ode45_events(|t, y| [y[1], -9.81], [0.0, 10.0], [10.0, 0.0], #{rtol: 1e-10, atol: 1e-12}, [ground])?;
    let stopped = sol.terminated;
    let found = sol.events;
    let landing = found[0]["t"];
    log_info(`terminated = ${stopped}`);   // true
    log_info(`landing time = ${landing}`);   // the square root of 2 * 10 / 9.81
}

The second example solves a stiff problem, y' = -50 y from y(0) = 1 over 0 to 0.1, with the Jacobian supplied. The Jacobian is the one-by-one matrix [[-50.0]]. The exact end value is exp(-5), about 0.0067. Because the Jacobian is given, the solver spends no right-hand side evaluations on finite-difference Jacobians, so nfev_jac is 0.

Rune
use eustress::log_info;
use eustress::realism::numerics;

pub fn on_init() {
    let opts = #{rtol: 1e-8, atol: 1e-12, jacobian: |t, y| [[-50.0]]};
    let sol = numerics::ode15s_events(|t, y| [-50.0 * y[0]], [0.0, 0.1], [1.0], opts, [])?;
    let y_end = sol.y_last()[0];
    let by_differences = sol.nfev_jac;
    log_info(`y(0.1) = ${y_end}`);   // about 0.0067
    log_info(`finite-difference evaluations = ${by_differences}`);   // 0
}

The third example turns on dense output and reads the falling ball at t = 1 s, before it lands. By hand the height is 10 - 9.81 / 2 = 5.095 m and the velocity is -9.81 m/s; the test checks both to 1e-8.

Rune
use eustress::log_info;
use eustress::realism::numerics;

pub fn on_init() {
    let ground = #{g: |t, y| y[0], terminal: true, direction: -1};
    let opts = #{rtol: 1e-10, atol: 1e-12, dense: true};
    let sol = numerics::ode45_events(|t, y| [y[1], -9.81], [0.0, 10.0], [10.0, 0.0], opts, [ground])?;
    let state = sol.eval(1.0)?;
    let height = state[0];
    let speed = state[1];
    log_info(`height = ${height}`);   // 5.095 to the solver tolerance
    log_info(`velocity = ${speed}`);   // -9.81 to the solver tolerance
}

05Options

Tolerances

The relative tolerance defaults to 1e-3 and the absolute tolerance to 1e-6, the same defaults as MATLAB. The relative tolerance must be positive and the absolute tolerance must not be negative. Tighter tolerances give smaller errors at the cost of more steps; the test suite checks that the error shrinks as the tolerance does.

A script sets the tolerances in the options table: rtol and atol, both numbers. Write them as {rtol = 1e-8, atol = 1e-10}. Write them as #{rtol: 1e-8, atol: 1e-10}. A name the solver does not know is an error that lists the valid names, so a misspelling such as reltol cannot pass silently; the message reads unknown option reltol; the options are: rtol, atol, ... and continues with the rest of the list.

Step Limits

OptionDefaultRule
First stepChosen automaticallyMust be positive when given; the solver limits it to the span and to the largest step
Largest stepNo ceilingMust be positive
Step budget10 million attempted stepsAccepted and rejected steps both count; at the budget the solve fails
Requested timesNoneSee Output at Requested Times
Dense outputOffTurn on to evaluate the solution at any time after the solve; Rune sets it with dense: true in the options of a *_events solverLuau has no such option

A solver stops at the end of the span, at a terminal event, at a step size underflow or at the step budget. The last two are errors. Setting a small step budget is the way to bound the work of a solve you cannot cancel.

A script names these options first_step, max_step, max_steps (the step budget, a whole number) and t_eval (an array of numbers). The base solvers have no dense-output option; the *_events solvers add dense. A table such as {max_steps = 100000, max_step = 0.1} sets them. An object such as #{max_steps: 100000, max_step: 0.1} sets them. With max_steps a script bounds the work of a solve in the way described above.

When a Solve Fails

A solve that cannot finish returns an error and no partial result, because an unfinished integration is not a usable answer. The error kinds and message text are:

CauseError kindMessage text
Step size underflow in ode45, ode23, ode23s or ode_radauno convergenceode: step size underflow at t = 0.99...; the problem may be stiff or singular for ode45 and ode23; the same text with ode23s or ode_radau in place of ode for those two
Step size underflow in ode15sno convergenceode15s: step size underflow at t = ...; the problem may be stiff or singular. With rtol = 1e-10 the backward-difference formulas may be out of digits here: use ode_radau for tolerances this tight (the rtol in the text is the one you set)
rtol below 1000 times machine epsilon in ode15sinvalid argumentode15s: rtol = 1e-14 is below what the backward-difference formulas can deliver (about 2e-13); use ode_radau
Step budget reachedno convergenceode: step budget of N exhausted at t = ... (the solver name replaces ode for the stiff solvers)
Empty or non-finite initial state, or a non-finite spaninvalid argumentode: y0 must be a non-empty finite vector, ode: tspan must be finite
A tolerance or step option out of rangeinvalid argumentode: rtol must be positive and atol non-negative, ode: max_step must be positive, ode: first_step must be positive

A finite-time blow-up, such as y' = y^2 from y(0) = 1 on a span of 0 to 2, is reported as an error and does not loop forever; the test suite checks that. A step size underflow usually means the problem is stiff or has a singularity: try a stiff solver, or check the right-hand side near the time reported.

A failed solve is a script error that pcall catches. A failed solve returns Err with a string. The kind (invalid argument or no convergence) is the start of the solver's own message text, after the routine prefix, and a script reads it by looking at that text. After the prefix Numerics.ode45:numerics::ode45:, a script sees the kind and the message text in the table. A script gets no partial result from a failed solve.

06In a Space

Using a Solver in a Script

A solve is one call that runs to the end. It cannot be cancelled from outside and reports no progress while it runs. Bound the work with a terminal event or a step budget. With one thread, which is the default, a solve returns the same bits on every run.

A script call is synchronous: the script waits while the solver runs, and your right-hand side function runs once per evaluation, so the cost of a solve grows with the cost of that function. Put max_steps in the options to bound the work. The times on the Performance page are of the Rust routines called directly; a script call adds the cost of converting tables to arrays and back, and that cost is not measured on this page.

A solve has no connection to the simulation clock or to physics. The time t is an argument of your function and the span is two numbers you pass; the solver advances its own time variable inside the call and does not advance the simulation clock or a physics step.

07What Is Not Covered

Missing Solvers and Alternatives

These MATLAB routines are not in the library. Where the table gives an alternative, it is the nearest one.

Not coveredUse instead
ode113ode45 with a tight tolerance
ode23t, ode23tbode15s or ode23s
Differential-algebraic equations and mass matrices (ode15i)Eliminate the algebraic variables, then use ode15s
dde23 (delay equations)No equivalent
bvp4c (boundary-value problems)No equivalent; a boundary-value problem can be shot with ode45 inside fsolve in Rune or in the Rust crate; Luau does not reach fsolve
ode78, ode89ode45 with a tight tolerance, which takes more steps for the same accuracy
pdepeDiscretize in space by hand (the method of lines), then use ode15s

08What's Next

Where to Go from Here

Optimization covers fzero, fminsearch and fminunc, which Luau and Rune reach, and fsolve, which solves the systems of equations that a shooting method for a boundary-value problem needs, and lsqnonlin, which fits model parameters to data, which Rune reaches and Luau does not.

Calculus and Signal covers integration of functions and of sampled data, interpolation and filtering. Control Design covers transfer-function and state-space models and controller design, and Performance holds the measured step counts.

Loading Eustress Engine...