Initial value problems and Euler’s method

Part 8 — Ordinary differential equations

Numerical analysis for biologists

About this lecture

Most models in biology say how fast something changes, not what it is: growth, decay, infection, binding. Those are ordinary differential equations (ODEs). Very few have a formula for the solution, so we step through time numerically.

  • An ODE model is rate in − rate out. With a starting value it is an initial value problem.
  • Euler’s method: follow the slope for a short step h, recompute the slope, repeat. Ten lines of code.
  • Its error: local O(h^2) per step, global O(h) at the end. Order 1: halving h halves the error, read off a log–log plot.
  • It can fail: too large a step gives negative concentrations, spurious boom–bust cycles, or oscillations that grow without end.
  • Systems (the SIR epidemic) and higher-order equations (a 24-hour oscillator) use the same method, with vectors.
  • Biology: exponential and logistic growth (exact solution known, so we can measure errors), the SIR model.

Recap: Euler already failed once

In Why numerical analysis? we stepped drug clearance C' = -kC (k = 0.8 per hour) forward with 3-hour steps:

k <- 0.8; h <- 3
C <- numeric(9); C[1] <- 10                  # mg/L
for (i in 1:8) C[i + 1] <- C[i] - h * k * C[i]
signif(C, 2)
# [1]   10  -14   20  -27   38  -54   75 -110  150
  • Each step multiplies by 1 - hk = -1.4: negative concentrations, growing without bound.
  • With h = 0.5 the factor is 0.6 and the answer is fine.
  • Today: where that formula comes from, how accurate it is when it works, and how to know which case you are in.

ODEs as models: rate in − rate out

An ODE says how fast a quantity changes, from what is known about flows:

Model ODE Rates
Drug clearance C' = -kC out: k = 0.8 per hour
mRNA level m' = \alpha - \delta m in: \alpha = 10 per min; out: \delta = 0.2 per min
Logistic growth N' = rN\,(1 - N/K) r = 0.8 per hour, K = 1.2 (OD)
  • Together with a start value this is an initial value problem (IVP): y'(t) = f(t, y), \qquad y(t_0) = y_0.
  • f gives the slope at every time and state. Solving the IVP means finding the curve y(t) that starts at y_0 and has slope f everywhere.

Exponential and logistic growth: exact answers

From calculus:

  • N' = rN has N(t) = N_0 e^{rt}. Grows for ever.
  • N' = rN(1 - N/K) has (separation of variables) N(t) = \frac{K}{1 + (K/N_0 - 1)\,e^{-rt}}, \qquad K = 1.2,\ N_0 = 0.05,\ r = 0.8 \text{ per hour}.
K <- 1.2; N0 <- 0.05; r <- 0.8
exact <- function(t) K / (1 + (K / N0 - 1) * exp(-r * t))
round(exact(0:5), 4)
# [1] 0.0500 0.1059 0.2126 0.3888 0.6193 0.8443
  • We use the logistic because we know the answer: every error today is measured, not guessed.
  • Real models (SIR, gene circuits, pharmacokinetics with several compartments) have no formula. That is why we need numerics.

Direction field: the ODE as a picture

  • At each point (t, N) draw a short line with slope f(t, N) = rN(1 - N/K).
  • A solution follows the lines. Different start values give different curves; they never cross.
  • N = 0 and N = K are equilibria (slope 0). Steepest growth at N = K/2.

Euler’s method: follow the slope

Take a small step h along the tangent, then look again:

y_{n+1} = y_n + h\,f(t_n, y_n), \qquad t_{n+1} = t_n + h.

  • From Taylor: y(t + h) = y(t) + h\,y'(t) + \tfrac{h^2}{2}\,y''(\xi), and y'(t) = f(t, y). Euler drops the h^2 term.
  • One f evaluation per step. y_n is our approximation to y(t_n).
  • The forward difference from Numerical differentiation, rearranged: \dfrac{y_{n+1} - y_n}{h} = f(t_n, y_n).

Euler by hand

Logistic growth, h = 1 hour, f(N) = 0.8\,N\,(1 - N/1.2):

n t_n N_n f(N_n) N_{n+1} = N_n + 1 \cdot f(N_n) exact N(t_{n+1})
0 0 0.05 0.8 \cdot 0.05 \cdot 0.9583 = 0.03833 0.08833 0.10587
1 1 0.08833 0.8 \cdot 0.08833 \cdot 0.9264 = 0.06547 0.15380 0.21263
2 2 0.15380 0.8 \cdot 0.15380 \cdot 0.8718 = 0.10727 0.26107 0.38879
  • Euler is behind the true curve: the slope keeps increasing during each step, and Euler uses the slope at the start.
  • After 3 h the error is 0.26 - 0.39 = -0.13: a third of the true value. h = 1 is too big here.

Euler in R

euler <- function(f, t0, y0, h, n) {
  t <- t0 + (0:n) * h
  y <- numeric(n + 1); y[1] <- y0         # R vectors start at index 1
  for (i in 1:n) y[i + 1] <- y[i] + h * f(t[i], y[i])
  data.frame(t = t, y = y)
}
f <- function(t, N) r * N * (1 - N / K)    # f(t, y), even if t is unused
out <- euler(f, 0, N0, h = 1, n = 5)
round(out$y, 4)
# [1] 0.0500 0.0883 0.1538 0.2611 0.4245 0.6439
  • The loop is the whole method. f always takes (t, y), so the same euler works for every ODE.
  • The first values match the hand table.

Smaller steps, closer to the truth

  • Error at t = 5 h: -0.20 with h = 1, -0.094 with h = 0.5, -0.017 with h = 0.1.
  • Error roughly proportional to h. Why, and how to check it?

Local and global error

  • Local error: error made in one step, starting on the exact curve through the previous point. From Taylor: \tfrac{h^2}{2}\,y'', so O(h^2).
  • Global error: y_n - y(t_n), everything accumulated since t_0.

Why global error is O(h)

  • One step: local error \approx \tfrac{h^2}{2}\,y''. Check on the first logistic step, y''(0) = 0.0281:

    h 1 0.5 0.25 0.1
    local error 0.0175 0.0039 0.00093 0.000144
    predicted \tfrac{h^2}{2}y''(0) 0.0141 0.0035 0.00088 0.000141

    Halving h divides the local error by about 4.

  • To reach time T takes n = T/h steps. Adding up T/h local errors of size C h^2: \text{global error} \approx \frac{T}{h}\cdot C h^2 = C\,T\,h = O(h).

  • Halving h makes each step 4× more accurate but doubles the number of steps: the total improves 2×. Euler is order 1.

Measure the order

exact <- function(t) K / (1 + (K / N0 - 1) * exp(-r * t))
h   <- 2^-(0:8)                               # 1, 1/2, ..., 1/256 hours
err <- sapply(h, function(h)
  abs(tail(euler(f, 0, N0, h, 5 / h)$y, 1) - exact(5)))
signif(err, 3)
# [1] 0.200000 0.094000 0.044400 0.021400 0.010500 0.005220 0.002600 0.001300
# [9] 0.000647
signif(err[-9] / err[-1], 3)                  # ratio when h is halved
# [1] 2.13 2.12 2.07 2.04 2.02 2.01 2.00 2.00
coef(lm(log10(err) ~ log10(h)))[2]            # slope on log-log axes
# log10(h)
# 1.031108
  • Halving h halves the error: ratio 2 = 2^1, slope 1. Order p would give ratio 2^p.

Order on a log–log plot

  • Global error: slope 1. Local (one-step) error: slope 2. Parallel lines would mean the same order.
  • Check your own solver this way: a slope that is not the expected order means a bug.

Without the exact answer: halve the step

Usually there is no formula. Run twice, with h and h/2:

y1 <- tail(euler(f, 0, N0, 0.1, 50)$y, 1)       # h = 0.1
y2 <- tail(euler(f, 0, N0, 0.05, 100)$y, 1)     # h = 0.05
c(y1, y2, y1 - y2, y2 - exact(5))
# [1]  0.827288203  0.835925961 -0.008637758 -0.008395457
  • Order 1: y_h \approx y + Ch and y_{h/2} \approx y + Ch/2, so y_h - y_{h/2} \approx Ch/2 \approx the error of y_{h/2}. Here -0.0086 vs the true -0.0084.
  • Cost: the error at t = 5 is about 0.17\,h. Four correct digits (10^{-4}) need h \approx 6\times10^{-4}: 8300 steps. Six digits: 830 000.
  • Order 1 is cheap per step and expensive per digit. Higher order: Runge–Kutta and adaptive step size.

Instability: back to drug clearance

On C' = -kC each Euler step multiplies by 1 - kh:

  • 0 < kh < 1: decays, like the truth. \;1 < kh < 2: decays, but flips sign every step.
  • kh > 2: |1 - kh| > 1, grows without bound. Stable only for h < 2/k = 2.5 h.

Instability in a nonlinear model

round(tail(euler(f, 0, N0, 3, 40)$y, 4), 3)
# [1] 1.431 0.770 1.432 0.767
  • Near K, the logistic behaves like y' = -r\,(N - K): the same test equation with rate r.
  • Stable only for h < 2/r = 2.5 h. With h = 3 (rh = 2.4), Euler settles into a boom–bust cycle 0.77 ↔︎ 1.43.
  • A confident wrong answer: a clean, repeating cycle that the true model does not have. Check: halve the step. The cycle disappears.

Try it: step through Euler

Systems of ODEs: the SIR epidemic

Susceptible S, infected I, recovered R in a population of N = 10\,000:

S' = -\beta \frac{SI}{N}, \qquad I' = \beta\frac{SI}{N} - \gamma I, \qquad R' = \gamma I

  • \beta = 0.3 per day (infectious contacts), \gamma = 0.1 per day (recovery: 10 days infectious). R_0 = \beta/\gamma = 3.
  • Start: S = 9990, I = 10, R = 0. Rate in − rate out again: \beta SI/N flows from S to I, \gamma I from I to R.
  • Vector form: \mathbf y = (S, I, R), \mathbf y' = \mathbf f(t, \mathbf y). Euler is unchanged: \mathbf y_{n+1} = \mathbf y_n + h\,\mathbf f(t_n, \mathbf y_n).

SIR in R

beta <- 0.3; gamma <- 0.1; N <- 10000       # per day; R0 = beta/gamma = 3
sir <- function(t, y) {
  S <- y[1]; I <- y[2]
  c(-beta * S * I / N, beta * S * I / N - gamma * I, gamma * I)
}
euler_sys <- function(f, t0, y0, h, n) {    # one row per time point
  Y <- matrix(0, n + 1, length(y0)); Y[1, ] <- y0
  for (i in 1:n) Y[i + 1, ] <- Y[i, ] + h * f(t0 + (i - 1) * h, Y[i, ])
  Y
}
Y <- euler_sys(sir, 0, c(9990, 10, 0), h = 1, n = 160)
c(peak = max(Y[, 2]), day = which.max(Y[, 2]) - 1)
#     peak      day
# 3127.315   41.000
  • The only change from euler: y is a vector, so the solution is a matrix (time × variable).

SIR: how accurate is the peak?

  • Exact peak: I_{\max} = S_0 + I_0 - \tfrac{N}{R_0}\bigl(1 + \ln\tfrac{R_0 S_0}{N}\bigr) = 3008. Euler: 3127 (h = 1 d), 3020 (h = 0.1 d). Order 1 again.
  • S + I + R = 10\,000 to 10^{-11} for every h: Euler keeps sums exactly. A conservation check finds bugs, not step-size error.

Higher-order ODEs → first-order systems

A 24-hour rhythm in its simplest form: the deviation x of a clock protein from its mean obeys x'' = -\omega^2 x, \qquad \omega = \frac{2\pi}{24} \text{ per hour}, \qquad x(0) = 1,\ x'(0) = 0. Exact solution: x(t) = \cos \omega t, period 24 h.

Recipe: name each derivative except the highest as a new variable.

  • y_1 = x, y_2 = x'. Then y_1' = y_2 and y_2' = x'' = -\omega^2 y_1: \begin{pmatrix} y_1 \\ y_2 \end{pmatrix}' = \begin{pmatrix} y_2 \\ -\omega^2 y_1 \end{pmatrix}, \qquad \mathbf y(0) = \begin{pmatrix} 1 \\ 0 \end{pmatrix}.
  • An order-m equation becomes m first-order ones; it needs m initial values. Every solver only handles \mathbf y' = \mathbf f(t, \mathbf y).

Euler on an oscillation: it spirals out

w <- 2 * pi / 24                       # one cycle per 24 h
osc <- function(t, y) c(y[2], -w^2 * y[1])
for (h in c(1, 0.1, 0.01)) {
  Y <- euler_sys(osc, 0, c(1, 0), h, n = 240 / h)
  x <- Y[nrow(Y), ]
  cat(h, sqrt(x[1]^2 + (x[2] / w)^2), "\n")   # amplitude after 10 days; exact: 1
}
# 1 2849.977
# 0.1 2.275467
# 0.01 1.085723
  • Each step multiplies the amplitude by \sqrt{1 + \omega^2 h^2} > 1, for every h. No step is small enough to be stable for long times.

The spiral

  • Left: h = 0.1 h, the amplitude grows by 8.6 % per day. Right: h = 1 h, the orbit in the (x, x'/\omega) plane spirals outwards instead of closing.
  • Check: track a quantity that should stay constant (here the amplitude). Drift means step-size error.

Before you trust an ODE solution

  • Halve the step and compare. If the answer moves in a digit you care about, the step was too large.
  • Measure the order on a test problem with a known answer (logistic): slope 1 for Euler. Another slope means a bug.
  • Stability: for each decay rate k in the model, need h < 2/k. Negative concentrations, sign-flipping or sudden cycles are warning signs.
  • Plausibility and invariants: concentrations \ge 0; conserved totals (S + I + R) catch typos; quantities that should be constant (an amplitude) catch step-size error.
  • Plot the solution, and look at it at the resolution of the steps.

Summary

  • An ODE model is rate in − rate out; with a start value it is an initial value problem y' = f(t, y), y(t_0) = y_0. The direction field shows f as slopes.
  • Euler: y_{n+1} = y_n + h\,f(t_n, y_n), the first-order Taylor step. Ten lines of code.
  • Local error O(h^2), global error O(h): order 1, slope 1 on a log–log plot. Without an exact solution, the change when h is halved estimates the error. Six digits on the logistic: 830 000 steps.
  • Instability: on y' = -ky each step multiplies by 1 - kh; need h < 2/k. Too large a step gives negative concentrations or a spurious cycle; on an oscillation Euler spirals out for every h.
  • Systems: same formula with vectors (SIR). Higher-order ODEs: introduce y_2 = x', … to get a first-order system.

Next: Runge–Kutta and adaptive step size: higher order, automatic step control, and the library solvers deSolve::ode and solve_ivp.