Fundamentals / Numerical mathematics

Numerical ordinary differential equations

Derive and compare time integrators, preserve physical invariants, and use sensitivities and shooting to solve for trajectories and boundary data.

Prerequisites First-order differential equations and exponentials.

Investigate with OneSimulation Compare time-step error with conservation

Read the subject in depth

Each volume develops its arguments in sequence, with worked problems and links to experiments.

  • Dynamics and numerical time integration

    Turn a differential model into a time step. Track accuracy, stability and structural properties separately in a computable physical or mathematical example.

How the course fits together

  1. Chapters 1–4

    Integrate a rate over one step. Local defects accumulate into global error, additional Runge–Kutta stages cancel Taylor terms, and stiffness can impose a stability limit even on a slowly varying solution. Multistep formulas reuse earlier information.

  2. Chapters 5–8

    Estimate error to select the step size, then ask what structure a time update preserves. Exponential integration evolves linear modes exactly and splitting separates processes that can each be evolved simply.

  3. Chapters 9–12

    Construct a reversible Verlet step, differentiate a trajectory with respect to a parameter, solve a boundary condition by shooting, and enforce algebraic constraints that restrict permissible states.

Chapters

  1. Initial values and propagated error

    Derive an error bound for forward Euler and distinguish a poor approximation of a well-posed trajectory from uncertainty in the starting state.

  2. Runge–Kutta stages and order

    Construct a two-stage second-order integrator from Taylor conditions and calculate how different stage choices affect autonomous and time-dependent problems.

  3. Absolute stability and stiffness

    Determine the step sizes that damp a decaying mode and explain why fast, physically uninteresting modes can dominate the cost of explicit integration.

  4. Multistep formulas and parasitic modes

    Derive Adams–Bashforth and BDF formulas from interpolation, test a characteristic polynomial and determine whether starting errors survive refinement.

  5. Adaptive steps and event locations

    Estimate local integration error with a low–high order pair, choose a dimensionally consistent tolerance and bracket a zero of an event function in time.

  6. Energy and geometric integration

    Compare three time updates on a conservative oscillator and explain why a method can have small short-term state error yet distort an orbit over many periods.

  7. Variation of constants and exponential steps

    Integrate a stiff linear decay exactly while approximating only its slowly changing forcing term.

  8. Operator splitting and noncommuting flows

    Determine how the order of two exact substeps affects a coupled evolution and recover second order by a symmetric composition.

  9. Störmer–Verlet and a discrete invariant

    Derive the leapfrog update, identify its oscillatory stability interval and quantify the difference between bounded energy and correct phase.

  10. Tangent equations and adjoint outputs

    Compute how an observed final state changes when an initial state or a model parameter is perturbed.

  11. Shooting for two-point boundary values

    Turn a missing initial slope into a scalar root, measure the sensitivity of endpoint matching and recognise an unstable propagation direction.

  12. Differential–algebraic equations and consistency

    Derive a reduced evolution when an algebraic variable can be eliminated and find the hidden velocity constraint in a mechanical example.

Further chapters and interactive tutorials

  1. Implicit midpoint, reversibility and the phase of an oscillator

    Imagine integrating a mechanical trajectory forward, saving only its end state and then running the same method backward. Recovering the start is a stronger demand than obtaining a plausibly small one-step error. Even exact recovery does not guarantee that an oscillation peaked at the correct time.

  2. Splitting a stiff relaxation from a slowly varying drive

    A sensor tries to follow a changing reference while a fast relaxation damps departures. An explicit method may oscillate wildly even though the underlying transient decays monotonically. Treating the restoring term implicitly can resolve the slow motion using steps longer than the transient time. Whether those steps measure the transient accurately is a different question.

  3. Why a boundary value problem can be easier than its shooting equation

    A concentration decays across a slab, with concentrations known at both faces. Computing a solution from the first face alone can bring in an exponentially growing mode. Enforcing both faces together gives a different numerical problem with the same differential equation.

  4. How two decaying modes produce a growing signal

    Solve a triangular system exactly, derive the energy growth criterion and separate a real transient from numerical instability.

  5. Locating a grazing event between time steps

    Derive a sensitivity formula for event time, then measure how a harmless error in a trajectory can create or remove two threshold crossings.

  6. A constrained integrator can get the circle right and the clock wrong

    A frictionless bead moves on an ideal circular guide. Its exact path, speed and angular phase can all be calculated by hand. Use this unusually informative reference to derive RATTLE's two constraint corrections and see which numerical errors would escape a camera that measured position alone.

Computational notebooks

Run the Python calculations in your browser and compare the figures with the derivations.

Problem sheets

Sheets 1–6 accompany the first twelve chapters. The final projects bring several methods together. Attempt each stage before opening its worked solution.

  1. From one update to a trajectoryFor chapters 1 and 2

    Set up a global error recurrence, verify Runge–Kutta order conditions and identify the role of explicitly time-dependent forcing.

  2. Damping and multistep memoryFor chapters 3 and 4

    Locate a stability region, compare two implicit formulas in the stiff limit and test whether a recurrence transports initial errors consistently.

  3. Events and long trajectoriesFor chapters 5 and 6

    Adapt a time step to a tolerance, analyse a grazing event and estimate phase drift on an energy-preserving orbit.

  4. Linear response and split flowsFor chapters 7 and 8

    Separate errors caused by a changing source from errors caused by composing noncommuting dynamics.

  5. Long trajectories and sensitivitiesFor chapters 9 and 10

    Check numerical phase, derive the tangent contribution from initial data, and verify an adjoint for an accumulated observation.

  6. Boundary and algebraic conditionsFor chapters 11 and 12

    Recover missing initial data, measure shooting amplification, and calculate a consistent implicit step for a constrained state.

  7. Project · Choose a time integrator from measurements

    A velocity sensor monitors an oscillator with one nearly conservative coordinate and one rapidly relaxing auxiliary variable. Design distinct numerical checks for phase, damping and the conditioning of a boundary measurement.

  8. Differentiate a bouncing trajectory through an impact

    A camera records height at a fixed time after an object hits the floor. A nearby release height changes the impact time as well as the rebound speed. Compute the sensitivity that an estimator needs, and see why differentiating just the reset of velocity gives an incorrect answer even with an accurately located impact.

Final synthesis problem · Separate conservation, stability and accuracy in a decay calculation

Applied study

Distinguish stability, positivity and accuracy when stepping a model forward in time.

How does a short step change a long trajectory?

A well-mixed reactant A converts to B at rate \(kA\). In a closed vessel \(\dot A=-kA\) and \(\dot B=kA\). For \(A(0)=1\), the exact concentration of A is \(e^{-kt}\) in the chosen units, while \(A+B\) remains constant. A numerical scheme can preserve the total exactly and still put the wrong amount in each species.

Integrating the differential equation over one time interval gives

\[A_{n+1}=A_n-k\int_{t_n}^{t_{n+1}}A(t)\,dt.\]

Replacing the integrand by its left endpoint yields forward Euler, \(A_{n+1}=(1-z)A_n\) with \(z=kh\). Using the unknown endpoint instead gives backward Euler, \(A_{n+1}=A_n/(1+z)\). Each method replaces the exact amplification factor \(e^{-z}\) by a simpler function \(R(z)\).

Distinguish stability, positivity and accuracy

For the decay mode, forward Euler damps successive values when \(|1-z|<1\), or \(0<z<2\). Keeping an initially positive concentration nonnegative requires the stronger condition \(z\leq1\). At \(z=1.5\) the forward Euler values alternate in sign as their magnitudes shrink. Backward Euler has \(R(z)=1/(1+z)>0\) for every positive step, although a large step can still give a poor quantity of reactant.

Taylor expansion gives

\[e^{-z}=1-z+z^2/2+\cdots.\]

Euler misses a term of order \(h^2\) per step. Over a fixed time interval the number of steps is proportional to \(1/h\), producing first-order global error under stable propagation. Classical four-stage Runge–Kutta (RK4) evaluates intermediate slopes. On this linear problem its factor is

\[R_4=1-z+z^2/2-z^3/6+z^4/24.\]

It first differs from the exponential at order \(h^5\), giving fourth-order global convergence.

Test a hand calculation against the exact decay

Take \(k=0.8\) s⁻¹ and \(h=0.625\) s, giving \(z=0.5\). After two steps, the exact fraction remaining is

\[e^{-1}=0.36788.\]

Forward Euler gives \(0.5^2=0.25\) and backward Euler gives

\[(1/1.5)^2=0.44444.\]

Both give positive, decaying sequences, but one consumes too much A and the other too little. The signs follow from \(1-z<e^{-z}<1/(1+z)\) for \(z>0\).

RK4 gives \(R_4(0.5)=0.6067708\), hence \(A_2\simeq0.36817\). Comparing all methods at the same physical time separates time error from a simple difference in how long the reaction has proceeded.

Problem class

Keep the chemical interpretation

With \(k=0.8\) s⁻¹, find the forward Euler upper step for nonnegative concentrations and the upper stability boundary. What happens exactly at the first bound?

Show the calculation

Nonnegativity gives

\[h\leq1/k=1.25\,\mathrm{s}.\]

The decaying stability interval has \(h<2/k=2.50\) s. At \(h=1.25\) s the method sends all remaining A to B in one step. The exact solution still contains \(e^{-1}\) of the starting A. Thus respecting a nonnegativity bound alone permits considerable error.

Measure an order from two runs

Suppose a step halving reduces the largest RK4 error over the same time interval from \(2.00\times10^{-8}\) to \(1.22\times10^{-9}\) mol/m³. Estimate the observed order. Explain what a mass-balance test would miss.

Show the calculation

Assuming \(E_h\approx C h^p\), take \(p=\log_2(E_h/E_{h/2})\approx4.03\). For these equations the stage increments of A and B are equal and opposite. Their sum can remain at the initial total throughout either run even when both concentrations have sizable individual errors.

OneSimulation laboratory

Compare time-step error with conservation

Compare recorded OneSimulation runs on this page. To test your own inputs, download the Python model and run the model in an activated OneSimulation environment.

Run the isothermal reaction from \(A=1,\ B=0\) mol/m³ to \(t=5/k=6.25\) s. Measure the maximum A error over all stored times and the drift of \(A+B\). First double the number of RK4 steps. Then restore 100 steps and change the time integrator. Download the Python experiment · OneSimulation first-order decay model.

python ordinary-differential-equations.py
python ordinary-differential-equations.py --steps 200
python ordinary-differential-equations.py --method euler
Errors in species A and in the conserved sum over five decay times.
Method, stepsFinal A (mol/m³)Max. A error (mol/m³)Max. drift (mol/m³)
RK4, 1000.006737948832.00 × 10⁻⁸4.44 × 10⁻¹⁶
RK4, 2000.006737947111.22 × 10⁻⁹3.33 × 10⁻¹⁶
Euler, 1000.005920529229.39 × 10⁻³4.44 × 10⁻¹⁶
Halving the RK4 step reduces the largest concentration error by about sixteen. The logarithmic axis also shows the much larger Euler error at 100 steps.
Halving the RK4 step reduces the largest concentration error by about sixteen. The logarithmic axis also shows the much larger Euler error at 100 steps.

As a fourth run, try --method euler --steps 5. This lands exactly on the nonnegativity limit. Predict both the final concentration and the largest error before running it.

Change parameters · Change the laboratory inputs

Change one input at a time and compare the recalculated curves with the argument above. The browser evaluates this small model locally; the accompanying numerical values state its assumptions and reference checks. Reset restores the reference inputs, and the data can be downloaded as CSV.

Problem sheet 1 · Predict when a conservative calculation loses all reactant

Advanced study across the subject

Each sequence connects the course to detailed chapters in neighbouring subjects. The complete course PDF includes their derivations, examples and exercises.

  1. Conserving motion in a physical system

    Track an invariant in phase space. Compare a rotating charge, parametrically driven oscillator and magnetic orbit. Use phase and energy as independent error measurements.

  2. Multiple scales and identifiable dynamics

    Derive a system with competing rates and ask which measurements can separate them. Resolve a decaying field and a coupled mechanical instrument before interpreting the numerical trajectory.

Integrate the same magnetic orbit with two time steppers. Measure phase drift and the change in kinetic energy separately.

A magnetic orbit that spirals outward in a perfect vacuum

Further reading

Compare specific topics with the university sources