---
title: "Lab: ODE and boundary-value solvers in code"
heading: Measuring order, stepping a stiff problem, shooting, and finite differences with Newton
eyebrow: A13 · Lesson 45 · Lab: ODE and boundary-value solvers in code
xp: 60
---

::: hook
Lessons 40 to 44 covered one-step and multistep methods, step control, stiffness and boundary-value problems. This lab puts them into code and measures them. You'll confirm AB2's order by halving the step, march BDF2 through a stiff problem at a step a thousand times longer than its fastest time constant, solve a linear boundary-value problem by shooting with RK4, solve another by finite differences with the Thomas algorithm, and solve a nonlinear one, the Bratu problem, by Newton's method on a tridiagonal system.
:::

::: play
- A method of order p has global error about $Ch^p$, so on log axes error against step is a straight line of slope p.
- The lines show order 1 (Euler), 2 (AB2, Heun, BDF2) and 4 (RK4) with the same constant. Halving h cuts their errors by 2, 4 and 16.
- Measuring this slope from two runs is the quickest test of whether a solver is coded correctly.
:::

```sim plot
view: graph
x: h = 0.001..0.5 log
y: err = 0.0000000000001..1 log
plot: 0.5*h | label: order 1
plot: 0.5*h^2 | label: order 2 | color: ch3
plot: 0.5*h^4 | label: order 4 | color: ch2
```

::: predict
## BDF2 steps through $\dot y = -1000(y - \cos t)$ with h = 0.01, ten times the fast time constant. What happens?

- [ ] It blows up, like any explicit method would
- [x] It tracks the slow solution accurately
- [ ] It oscillates around the solution forever
- [ ] It converges to zero

::: reveal
It tracks the slow solution, $y \approx \cos t + 0.001\sin t$, to about $10^{-5}$. BDF2 damps the fast mode at any step size, so the step only has to resolve the slow variation of $\cos t$. Forward Euler would need h < 0.002 just to stay stable.
:::
:::

::: nameit
## Measuring order

Run with h and h/2 and compare the errors at the same time: $p \approx \log_2\frac{e(h)}{e(h/2)}$. Start multistep methods with exact or high-order values, or the starting error will mask the method's order.

## BDF2 on a linear stiff problem

For $\dot y = \lambda(y - g(t))$, BDF2's implicit step solves in closed form: $y_{n+1} = \frac{4y_n - y_{n-1} - 2h\lambda g_{n+1}}{3 - 2h\lambda}$. Take the first step with backward Euler.

## Shooting with an IVP solver

Write the second-order ODE as a first-order system $(y, y')$, integrate with RK4 from a guessed slope, and adjust. For a linear problem with $y(0) = 0$, the end value is proportional to the slope, so one shot and a rescale suffice.

## Finite differences with Newton

For $y'' = f(y)$, the residual at each interior point is $F_i = \frac{y_{i+1} - 2y_i + y_{i-1}}{h^2} - f(y_i)$, and its Jacobian is tridiagonal with $-\frac{2}{h^2} - f'(y_i)$ on the diagonal and $\frac{1}{h^2}$ beside it. Newton's method, $y \leftarrow y - J^{-1}F$, usually converges in a handful of iterations from y = 0.
:::

::: example
## Measure AB2's order on $\dot y = -y$ to t = 1, starting each run with the exact $y_1 = e^{-h}$.

::: solution
1. **The errors.** With h = 0.1 the error at t = 1 is $1.46 \times 10^{-3}$, and with h = 0.05 it's $3.75 \times 10^{-4}$.
2. **The order.** The ratio is 3.90, so
   $$p \approx \log_2 3.90 = 1.96$$
   close to 2.
3. **Smaller steps.** The ratio approaches 4 as h shrinks; at large h the higher-order terms still show.
4. **The starting value.** If it had come from one Euler step, its $O(h^2)$ error would still leave AB2 second-order overall, but a cruder start would cap the observed order.

**Answer:** the measured order is about 1.96, close to 2.
:::
:::

::: example
## Solve the Bratu problem $y'' + e^y = 0$, $y(0) = y(1) = 0$, by finite differences and Newton's method.

::: solution
1. **Set up.** With 99 interior points ($h = 0.01$), start from y = 0. The residual is
   $$F_i = \frac{y_{i+1} - 2y_i + y_{i-1}}{h^2} + e^{y_i}$$
   and the Jacobian's diagonal is $-\frac{2}{h^2} + e^{y_i}$.
2. **Newton.** It converges in about four iterations, giving $y(0.5) = 0.1405406$.
3. **The exact solution.**
   $$y = -2\ln\frac{\cosh((x - 1/2)\theta/2)}{\cosh(\theta/4)}$$
   where θ = 1.51716 solves $\theta = \sqrt2\cosh\frac\theta4$. It gives $y(0.5) = 0.1405392$.
4. **The difference.** It is $1.4 \times 10^{-6}$, the $O(h^2)$ discretization error, and it falls by four when h halves.

**Answer:** $y(0.5) = 0.1405406$, against the exact 0.1405392.
:::
:::

::: check
given: e1 = 0.0015 | 0.004; r = 3.9 | 15.8
answer: log(r)/log(2)
tolerance: 0.5%

## A solver's error is {e1} at step h and {e1}/{r} at h/2. What order does that suggest?

::: right
Right. $p = \log_2\frac{e(h)}{e(h/2)}$.
:::

::: misses
- [log(r)] Use base 2, since the step halved.
- [any] $\log_2 r$.
:::
:::

::: check
given: k = 1000 | 10000; h = 0.01 | 0.1
answer: 1/sqrt(3 - 2*(-k*h))
tolerance: 0.5%

## BDF2 steps a mode decaying at rate {k} s⁻¹ with h = {h} s. By what factor does each step shrink that mode?

::: right
Right. $\frac{1}{\sqrt{3 - 2h\lambda}}$ with $h\lambda = -kh$: strong damping however large the step.
:::

::: misses
- [1/(1 + k*h)] That's backward Euler's factor.
- [any] For $h\lambda < -\frac12$, $\lvert r\rvert = \frac{1}{\sqrt{3 - 2h\lambda}}$.
:::
:::

::: check
kind: python

## Write `ab2_error(h)` that runs AB2 on $\dot y = -y$ to t = 1, starting from $y_0 = 1$ and the exact $y_1 = e^{-h}$, and returns the absolute error at t = 1. Set `e1 = ab2_error(0.1)`, `e2 = ab2_error(0.05)` and `order = log2(e1/e2)`.

```python starter
import math

def ab2_error(h):
    return h

e1, e2 = ab2_error(0.1), ab2_error(0.05)
order = math.log2(e1 / e2)
print(e1, e2, order)
```

```python solution
import math

def ab2_error(h):
    n = int(round(1 / h))
    y = [1.0, math.exp(-h)]
    for i in range(1, n):
        y.append(y[i] + h / 2 * (3 * (-y[i]) - (-y[i - 1])))
    return abs(y[n] - math.exp(-1))

e1, e2 = ab2_error(0.1), ab2_error(0.05)
order = math.log2(e1 / e2)
print(e1, e2, order)
```

```python tests
assert abs(e1 - 1.4642e-3) < 1e-6, f"With h = 0.1 the error is 1.46e-3; got {e1}."
assert 1.9 < order < 2.1, f"AB2 is second order; got {order}."
```

::: right
Right. $1.46 \times 10^{-3}$ and $3.75 \times 10^{-4}$: order 1.96.
:::
:::

::: check
kind: python

## Step $\dot y = -1000(y - \cos t)$ from y(0) = 1 to t = 1 with h = 0.01: one backward Euler step, then BDF2. Set `y_end`, and `ref` to the slow solution $\frac{10^6\cos 1 + 1000\sin 1}{10^6 + 1}$.

```python starter
import math

y_end = 1.0
ref = (1e6 * math.cos(1) + 1000 * math.sin(1)) / (1e6 + 1)
print(y_end, ref)
```

```python solution
import math

lam, h, n = -1000.0, 0.01, 100
y = [1.0]
y.append((y[0] - h * lam * math.cos(h)) / (1 - h * lam))
for i in range(1, n):
    t_next = (i + 1) * h
    y.append((4 * y[i] - y[i - 1] - 2 * h * lam * math.cos(t_next)) / (3 - 2 * h * lam))
y_end = y[n]
ref = (1e6 * math.cos(1) + 1000 * math.sin(1)) / (1e6 + 1)
print(y_end, ref)
```

```python tests
assert abs(y_end - ref) < 1e-5, f"BDF2 should track the slow solution 0.541143 at t = 1; got {y_end}."
```

::: right
Right. 0.5411433, on the slow solution, at a step ten times the fast time constant.
:::
:::

::: check
kind: python

## Write `rk4(f, y, t0, t1, n)` for systems (NumPy arrays). Solve $y'' = y$, $y(0) = 0$, $y(1) = 1$ by shooting: integrate $(y, y')$ from (0, 1) with 100 steps, and set `s` to the slope that hits the target.

```python starter
import numpy as np

def rk4(f, y, t0, t1, n):
    return np.array(y, float)

s = 1.0
print(s)
```

```python solution
import numpy as np

def rk4(f, y, t0, t1, n):
    h = (t1 - t0) / n
    t, y = t0, np.array(y, float)
    for _ in range(n):
        k1 = f(t, y)
        k2 = f(t + h / 2, y + h / 2 * k1)
        k3 = f(t + h / 2, y + h / 2 * k2)
        k4 = f(t + h, y + h * k3)
        y = y + h / 6 * (k1 + 2 * k2 + 2 * k3 + k4)
        t += h
    return y

f = lambda t, y: np.array([y[1], y[0]])
end = rk4(f, [0.0, 1.0], 0, 1, 100)[0]
s = 1.0 / end
print(s)
```

```python tests
import math
assert abs(s - 1 / math.sinh(1)) < 1e-9, f"The slope is 1/sinh(1) = 0.850918; got {s}."
```

::: right
Right. 0.850918: one shot, then a rescale, because the problem is linear.
:::
:::

::: check
kind: python

## Write `thomas(a, b, c, d)` solving a tridiagonal system (a below, b on, c above the diagonal). Use it to solve $y'' = 4y$, $y(0) = 1$, $y(1) = 0$ with N interior points, and set `e9` and `e19` to the worst errors for N = 9 and 19 against $\frac{\sinh 2(1 - x)}{\sinh 2}$.

```python starter
import numpy as np

def thomas(a, b, c, d):
    return d / b

e9 = e19 = 1.0
print(e9, e19)
```

```python solution
import numpy as np

def thomas(a, b, c, d):
    n = len(d)
    cp, dp = np.zeros(n), np.zeros(n)
    cp[0], dp[0] = c[0] / b[0], d[0] / b[0]
    for i in range(1, n):
        m = b[i] - a[i] * cp[i - 1]
        cp[i] = c[i] / m if i < n - 1 else 0.0
        dp[i] = (d[i] - a[i] * dp[i - 1]) / m
    x = np.zeros(n)
    x[-1] = dp[-1]
    for i in range(n - 2, -1, -1):
        x[i] = dp[i] - cp[i] * x[i + 1]
    return x

def fd_error(N):
    h = 1 / (N + 1)
    a, c = np.ones(N), np.ones(N)
    b = -(2 + 4 * h * h) * np.ones(N)
    d = np.zeros(N)
    d[0] = -1.0
    y = thomas(a, b, c, d)
    x = np.arange(1, N + 1) * h
    return np.max(np.abs(y - np.sinh(2 * (1 - x)) / np.sinh(2)))

e9, e19 = fd_error(9), fd_error(19)
print(e9, e19)
```

```python tests
assert abs(e9 - 4.39e-4) < 1e-5, f"With 9 points the worst error is 4.4e-4; got {e9}."
assert 3.8 < e9 / e19 < 4.1, f"Halving h should cut the error by about 4; got {e9 / e19}."
```

::: right
Right. $4.4 \times 10^{-4}$, then $1.1 \times 10^{-4}$: second order, in O(N) work.
:::
:::

::: check
kind: python

## Solve the Bratu problem $y'' + e^y = 0$, $y(0) = y(1) = 0$ with 99 interior points by Newton's method from y = 0 (20 iterations, `np.linalg.solve` on the tridiagonal Jacobian is fine). Set `mid` to the middle value.

```python starter
import numpy as np

mid = 0.0
print(mid)
```

```python solution
import numpy as np

N = 99
h = 1 / (N + 1)
y = np.zeros(N)
for _ in range(20):
    F = (np.r_[y[1:], 0] - 2 * y + np.r_[0, y[:-1]]) / h**2 + np.exp(y)
    J = np.diag(-2 / h**2 + np.exp(y)) + np.diag(np.ones(N - 1) / h**2, 1) + np.diag(np.ones(N - 1) / h**2, -1)
    y -= np.linalg.solve(J, F)
mid = y[N // 2]
print(mid)
```

```python tests
assert abs(mid - 0.1405406) < 1e-6, f"With h = 0.01 the midpoint is 0.14054; got {mid}."
assert abs(mid - 0.1405392) < 5e-6, "It should be within the O(h^2) error of the exact 0.1405392."
```

::: right
Right. 0.1405406, within $1.4 \times 10^{-6}$ of the exact 0.1405392.
:::
:::

::: explain
## Why does measuring the error ratio under step halving test a solver so well?

::: model
A correctly coded method of order p has a global error that behaves like $Ch^p$ for small h, so halving h divides the error by $2^p$, whatever the constant C is. A coding slip, such as a wrong coefficient, a time argument off by one step, or a starting value from a cruder method, almost always lowers the observed order, even when the answers still look plausible. Measuring the ratio from two or three runs therefore checks the code against a property the correct method must have, without needing the exact answer to many digits, only one with an error well below the method's.
:::
:::

::: practice

::: check
given: e1 = 0.002 | 0.0005; r = 4.1 | 7.9
answer: log(r)/log(2)
tolerance: 0.5%

## Observed order from a ratio of {r}?

::: misses
- [any] $\log_2 r$.
:::
:::

::: check
given: k = 500 | 50000; h = 0.002 | 0.05
answer: 1/sqrt(3 - 2*(-k*h))
tolerance: 0.5%

## BDF2 damping per step, rate {k}, h = {h}?

::: misses
- [any] $\frac{1}{\sqrt{3 + 2kh}}$.
:::
:::
:::
