TExcelTAD
Home › Numerical Methods › Systems and Higher-Order Equations

Systems of ODEs

Most models have several interacting unknowns: predators and prey, position and velocity, concentrations of several chemicals. Numerically a system u′=f(t,u)\mathbf{u}' = \mathbf{f}(t, \mathbf{u}) is no harder than a single equation: the same methods apply with uu replaced by a vector. Higher-order equations are first rewritten as first-order systems.

Vector form

Every method of this part works verbatim for vectors. Euler's method, for example, is ui+1=ui+hf(ti,ui)\mathbf{u}_{i+1} = \mathbf{u}_i + h\mathbf{f}(t_i, \mathbf{u}_i). In NumPy the state is a 1D array and f\mathbf{f} returns an array of the same shape.

python · try it yourself
import numpy as np
from scipy.integrate import solve_ivp

def lotka_volterra(t, u, a=1.0, b=0.1, c=1.5, d=0.075):
    prey, pred = u
    return np.array([a * prey - b * prey * pred, -c * pred + d * prey * pred])

sol = solve_ivp(lotka_volterra, (0, 15), [10.0, 5.0], rtol=1e-9, dense_output=True)
for t in (0, 3, 6, 9, 12, 15):
    prey, pred = sol.sol(t)
    print(f"t = {t:2d}: prey {prey:7.3f}, predators {pred:7.3f}")
t =  0: prey  10.000, predators   5.000
t =  3: prey  31.846, predators  19.704
t =  6: prey  13.512, predators   3.602
t =  9: prey  16.750, predators  22.885
t = 12: prey  19.164, predators   3.098
t = 15: prey   9.780, predators  17.167

Higher order to first order

An mm-th order equation becomes mm first-order equations by introducing derivatives as new unknowns. The pendulum θ′′+gLsin⁡θ=0\theta'' + \frac{g}{L}\sin\theta = 0 with u1=θu_1 = \theta, u2=θ′u_2 = \theta':

u1′=u2,u2′=−gLsin⁡u1.u_1' = u_2, \qquad u_2' = -\frac{g}{L}\sin u_1.
python · try it yourself
import numpy as np
from scipy.integrate import solve_ivp

g_over_L = 9.81
def pendulum(t, u):
    return [u[1], -g_over_L * np.sin(u[0])]

for amp_deg in (5, 45, 90, 170):
    u0 = [np.radians(amp_deg), 0.0]
    # period: first return to the starting turning point, where theta' crosses 0 from + to -
    def turning(t, u): return u[1]
    turning.direction = -1
    sol = solve_ivp(pendulum, (0, 20), u0, events=turning, rtol=1e-10, atol=1e-12)
    T = sol.t_events[0][sol.t_events[0] > 1e-6][0]          # skip the event at t = 0

    print(f"amplitude {amp_deg:3d} deg: period {T:.5f} s (small-angle {2 * np.pi / np.sqrt(g_over_L):.5f} s)")
amplitude   5 deg: period 2.00702 s (small-angle 2.00607 s)
amplitude  45 deg: period 2.08626 s (small-angle 2.00607 s)
amplitude  90 deg: period 2.36784 s (small-angle 2.00607 s)
amplitude 170 deg: period 4.89352 s (small-angle 2.00607 s)

Large swings take longer, which the small-angle formula misses.

Many bodies

Systems of particles have one block of equations per particle. Writing the right-hand side with array operations keeps the code fast. Here are three bodies with gravity in the plane (units with G=1G = 1):

python · try it yourself
import numpy as np
from scipy.integrate import solve_ivp

m = np.array([1.0, 1.0, 1.0])
def nbody(t, u):
    pos = u[:6].reshape(3, 2); vel = u[6:].reshape(3, 2)
    d = pos[None, :, :] - pos[:, None, :]                 # d[i, j] = pos_j - pos_i
    r3 = np.sum(d**2, axis=2) ** 1.5 + np.eye(3)          # avoid division by zero on the diagonal
    acc = np.sum(m[None, :, None] * d / r3[:, :, None], axis=1)
    return np.concatenate([vel.ravel(), acc.ravel()])

# the figure-eight choreography (Chenciner-Montgomery initial data)
p = np.array([[-0.97000436, 0.24308753], [0.0, 0.0], [0.97000436, -0.24308753]])
v3 = np.array([-0.93240737, -0.86473146])
v = np.array([-v3 / 2, v3, -v3 / 2])
u0 = np.concatenate([p.ravel(), v.ravel()])
T = 6.32591398
sol = solve_ivp(nbody, (0, T), u0, method="DOP853", rtol=1e-12, atol=1e-12)
print(f"after one period, max change in positions: {np.max(np.abs(sol.y[:6, -1] - u0[:6])):.1e}")
print("total momentum:", np.round((m[:, None] * sol.y[6:, -1].reshape(3, 2)).sum(axis=0), 12) + 0)
after one period, max change in positions: 3.0e-08
total momentum: [0. 0.]

In software

  • solve_ivp expects fun(t, y) returning an array of shape (n,); vectorized=True lets it evaluate several states at once for finite-difference Jacobians.
  • Physics engines and molecular dynamics codes store positions and velocities in separate arrays and use specialized integrators (Long-Time Integration and Symplectic Methods).

Exercises

Exercise 1: Convert to a system

Write y′′′−y′+ty=cos⁡ty''' - y' + ty = \cos t as a first-order system.

Answer

u1′=u2u_1' = u_2, u2′=u3u_2' = u_3, u3′=cos⁡t+u2−tu1u_3' = \cos t + u_2 - tu_1.

Solution

With u1=yu_1 = y, u2=y′u_2 = y', u3=y′′u_3 = y'', the equation gives y′′′=cos⁡t+y′−tyy''' = \cos t + y' - ty.

Exercise 2: Initial conditions

What initial data does the system of exercise 1 need?

Answer

y(t0)y(t_0), y′(t0)y'(t_0) and y′′(t0)y''(t_0).

Solution

One value per first-order equation: u1(t0),u2(t0),u3(t0)u_1(t_0), u_2(t_0), u_3(t_0).

Exercise 3: A damped oscillator (code)

Solve x′′+0.4x′+4x=0x'' + 0.4x' + 4x = 0, x(0)=1x(0) = 1, x′(0)=0x'(0) = 0 with solve_ivp and compare x(5)x(5) with the exact solution e−0.2t(cos⁡ωt+0.2ωsin⁡ωt)e^{-0.2t}\left(\cos\omega t + \frac{0.2}{\omega}\sin\omega t\right), ω=3.96\omega = \sqrt{3.96}.

Answer

They agree to about 9 digits with rtol=1e-10.

Solution
python · try it yourself
import numpy as np
from scipy.integrate import solve_ivp
sol = solve_ivp(lambda t, u: [u[1], -0.4 * u[1] - 4 * u[0]], (0, 5), [1.0, 0.0], rtol=1e-10, atol=1e-12)
w = np.sqrt(3.96)
exact = np.exp(-1.0) * (np.cos(5 * w) + 0.2 / w * np.sin(5 * w))
print(f"{sol.y[0, -1]:.12f} {exact:.12f}")
-0.336851680563 -0.336851680590

Test yourself

A third-order scalar ODE becomes a first-order system of…

  1. 1 equation
  2. 2 equations
  3. 3 equations
  4. 6 equations

Euler's method for a system u′=f(t,u)\mathbf{u}' = \mathbf{f}(t, \mathbf{u}) is…

  1. applied to one component at a time with different steps
  2. ui+1=ui+hf(ti,ui)\mathbf{u}_{i+1} = \mathbf{u}_i + h\mathbf{f}(t_i, \mathbf{u}_i)
  3. not possible
  4. only for linear systems

In the pendulum, the period for large amplitude is…

  1. shorter than the small-angle value
  2. longer than the small-angle value
  3. the same
  4. zero