---
title: "Lab: boundary value problems in code"
heading: Finite differences, shooting and eigenvalues
eyebrow: A8 · Lesson 51 · Lab: boundary value problems
xp: 60
---

::: hook
An initial-value problem gives everything at one end and steps forward. A boundary-value problem gives conditions at both ends, so stepping from one end means guessing what you don't know there. Lesson 50 solved these by hand when a formula exists. In this lab you'll solve them numerically in the two standard ways: **finite differences**, which turn the equation into a tridiagonal linear system, and **shooting**, which guesses the missing slope and corrects it. Then you'll find a string's vibration modes as the eigenvalues of a matrix.
:::

::: play
- The curves are mode $n$ of a string or line fixed at both ends, $\sin(n\pi x)$, and its finite-difference approximation's eigenvalue against the exact $(n\pi)^2$.
- Low modes are resolved well by a 50-point grid. Raise $n$: as the wavelength shrinks toward the grid spacing, the finite-difference eigenvalue falls further below the true one.
- That's the general rule for discretized waves: a grid needs several points per wavelength.
:::

```sim plot
view: graph
x: x = 0..1
y: y = -1.2..1.2
slider: n = 1..20 step 1 = 1
plot: sin(n*pi*x) | label: mode n | samples: 600
readout: exact eigenvalue (nπ)² = (n*pi)^2 | digits: 5
readout: 50-point estimate = 4*50^2*sin(n*pi/100)^2 | digits: 5
```

::: predict
## Second-order finite differences solve $y'' = -5$ with $y(0) = y(1) = 0$ on a grid of only 10 intervals. How accurate is the answer at the grid points?

- [ ] About 1%, typical for so coarse a grid
- [ ] About 0.01%
- [x] Exact, apart from rounding
- [ ] Unusable

::: reveal
Exact. The central difference $\frac{y_{k+1} - 2y_k + y_{k-1}}{h^2}$ has an error proportional to $h^2y''''$, and the true solution here is a parabola, whose fourth derivative is zero. For any other solution the error shrinks by 4 each time $h$ halves.
:::
:::

::: nameit
## Finite differences

Divide $[0, L]$ into $n$ intervals of width $h = L/n$, and replace $y''$ at each interior point by

$$y''(x_k) \approx \frac{y_{k+1} - 2y_k + y_{k-1}}{h^2}$$

For $y'' = f(x)$ with known end values, that's $n - 1$ equations in the $n - 1$ interior values, with a tridiagonal matrix: $-2/h^2$ on the diagonal and $1/h^2$ beside it. Known end values move to the right side. The error is $O(h^2)$.

## Shooting

Turn the boundary-value problem into an initial-value problem with a guessed slope $s$ at the left end, integrate to the right end, and compare with the right-end condition. The mismatch is a function of $s$; find its zero by bisection or the secant method. For a linear equation the mismatch is linear in $s$, so two shots determine the answer exactly.

## Eigenvalues

$-y'' = \lambda y$ with $y(0) = y(1) = 0$ becomes $K\mathbf{y} = \lambda\mathbf{y}$ for the tridiagonal $K$ with $2/h^2$ on the diagonal and $-1/h^2$ beside it. Its eigenvalues are exactly

$$\lambda_n^{(h)} = \frac{4}{h^2}\sin^2\frac{n\pi h}{2}$$

which approach $(n\pi)^2$ as $h \to 0$ and fall below them for modes with few points per wavelength.
:::

::: example
## Set up the finite-difference system for $y'' = -5$, $y(0) = y(1) = 0$, with $h = 0.25$.

::: solution
1. **Unknowns.** The interior points are $x = 0.25$, 0.5 and 0.75, with unknowns $y_1, y_2, y_3$.
2. **One equation per point.** With $y_0 = y_4 = 0$, each equation is
   $$\frac{y_{k+1} - 2y_k + y_{k-1}}{0.0625} = -5$$
3. **The system.**
   $$16\begin{bmatrix}-2 & 1 & 0\\1 & -2 & 1\\0 & 1 & -2\end{bmatrix}\begin{bmatrix}y_1\\y_2\\y_3\end{bmatrix} = \begin{bmatrix}-5\\-5\\-5\end{bmatrix}$$
4. **Solve and check.** The solution is $(0.469, 0.625, 0.469)$, exactly $2.5x(1 - x)$ at those points: the middle value $\frac{5}{8} = 0.625$ is $\frac{qL^2}{8}$.

**Answer:** the three equations above, whose solution $(0.469, 0.625, 0.469)$ matches $2.5x(1 - x)$ exactly.
:::
:::

::: example
## Solve $y'' = 6x$ with $y(0) = 0$, $y(1) = 2$ by shooting.

::: solution
1. **Integrate with a guessed slope.** Integrating from $y(0) = 0$, $y'(0) = s$ gives
   $$y = x^3 + sx$$
   so $y(1) = 1 + s$.
2. **The mismatch is linear.** The mismatch $1 + s - 2$ is linear in $s$, as it must be for a linear equation.
3. **Two shots.** $s = 0$ misses by $-1$ and $s = 2$ misses by $+1$; interpolating gives $s = 1$.
4. **Nonlinear equations.** For a nonlinear equation the mismatch is curved, and the secant method takes a few more shots.

**Answer:** $y = x^3 + x$.
:::
:::

::: check
given: n = 10 | 20 | 50; L = 1 | 2
answer: -2*n^2/L^2
tolerance: 0.5%

## A finite-difference grid of {n} intervals on $[0, \given{L}]$ approximates $y''$. What is the diagonal entry of its matrix?

::: right
Right. $-2/h^2$ with $h = L/n$: {answer}.
:::

::: misses
- [-2/(L/n)] Divide by $h^2$, not $h$.
- [2*n^2/L^2] The center point enters with $-2$.
- [any] Not yet. The stencil is $\frac{y_{k+1} - 2y_k + y_{k-1}}{h^2}$.
:::
:::

::: check
given: N = 5 | 10; k = 2 | 3
answer: 4*N^2*sin(k*pi/(2*N))^2
tolerance: 0.5%

## What is the finite-difference estimate of the $k$ = {k} eigenvalue of $-y'' = \lambda y$ on $[0, 1]$ with {N} intervals?

::: right
Right. $\frac{4}{h^2}\sin^2\frac{k\pi h}{2}$ = {answer}, slightly below $(k\pi)^2$.
:::

::: misses
- [(k*pi)^2] That's the exact eigenvalue; the grid's estimate is a little lower.
- [any] Not yet. Use $\frac{4}{h^2}\sin^2\frac{k\pi h}{2}$ with $h = 1/N$.
:::
:::

::: check
kind: python

## Solve $y'' = -5$ on $[0, 1]$ with zero ends by finite differences, $n$ = 10 intervals. Set `err` to the largest difference from the exact $2.5x(1 - x)$ at the interior points.

```python starter
import numpy as np

err = 1.0
print(err)
```

```python solution
import numpy as np

n = 10
h = 1 / n
K = (np.diag([-2.0] * (n - 1)) + np.diag([1.0] * (n - 2), 1) + np.diag([1.0] * (n - 2), -1)) / h**2
y = np.linalg.solve(K, -5 * np.ones(n - 1))
x = np.linspace(h, 1 - h, n - 1)
err = np.max(np.abs(y - 2.5 * x * (1 - x)))
print(err)
```

```python tests
assert err < 1e-10, f"For a parabola, finite differences are exact apart from rounding; got an error of {err}."
```

::: right
Right. The stencil's error involves $y''''$, which is zero for a parabola.
:::
:::

::: check
kind: python

## Write `fd_error(n)` that solves $y'' = -\sin\pi x$ with zero ends on $n$ intervals and returns the largest error against the exact $\frac{\sin\pi x}{\pi^2}$. Set `ratio = fd_error(10) / fd_error(20)`.

```python starter
import numpy as np

def fd_error(n):
    return 1.0 / n

ratio = fd_error(10) / fd_error(20)
print(ratio)
```

```python solution
import numpy as np

def fd_error(n):
    h = 1 / n
    K = (np.diag([-2.0] * (n - 1)) + np.diag([1.0] * (n - 2), 1) + np.diag([1.0] * (n - 2), -1)) / h**2
    x = np.linspace(h, 1 - h, n - 1)
    y = np.linalg.solve(K, -np.sin(np.pi * x))
    return np.max(np.abs(y - np.sin(np.pi * x) / np.pi**2))

ratio = fd_error(10) / fd_error(20)
print(ratio)
```

```python tests
assert 3.8 < ratio < 4.2, f"A second-order method's error should fall by about 4 when h halves; got {ratio}."
assert fd_error(10) < 1e-3, "With 10 intervals the error is already below 1e-3."
```

::: right
Right. Halve $h$ and the error falls by 4: second order, as the stencil's $h^2$ error term says.
:::
:::

::: check
kind: python

## Solve $y'' = 6x$ with $y(0) = 0$ and $y(1) = 2$ by shooting: write `shoot(s)` returning $y(1) - 2$ after integrating from $y(0) = 0$, $y'(0) = s$ with RK4 (1000 steps), then bisect on $[0, 3]$ (50 steps) and set `s_star`.

```python starter
def shoot(s):
    return s - 2

s_star = 2.0
print(s_star)
```

```python solution
def shoot(s):
    def f(x, y, v):
        return v, 6 * x
    x, y, v, h = 0.0, 0.0, s, 0.001
    for _ in range(1000):
        k1 = f(x, y, v)
        k2 = f(x + h / 2, y + h / 2 * k1[0], v + h / 2 * k1[1])
        k3 = f(x + h / 2, y + h / 2 * k2[0], v + h / 2 * k2[1])
        k4 = f(x + h, y + h * k3[0], v + h * k3[1])
        y += h / 6 * (k1[0] + 2 * k2[0] + 2 * k3[0] + k4[0])
        v += h / 6 * (k1[1] + 2 * k2[1] + 2 * k3[1] + k4[1])
        x += h
    return y - 2

lo, hi = 0.0, 3.0
for _ in range(50):
    mid = (lo + hi) / 2
    if shoot(lo) * shoot(mid) <= 0:
        hi = mid
    else:
        lo = mid
s_star = (lo + hi) / 2
print(s_star)
```

```python tests
assert abs(s_star - 1) < 1e-6, f"The missing slope is 1 (y = x^3 + x); got {s_star}."
assert abs(shoot(0) + 1) < 1e-9 and abs(shoot(2) - 1) < 1e-9, "shoot(0) = -1 and shoot(2) = +1: the mismatch is linear in s."
```

::: right
Right. Bisection doesn't care that the problem is linear; for a nonlinear equation the same loop still finds the slope.
:::
:::

::: check
kind: python

## Build the $49 \times 49$ matrix for $-y'' = \lambda y$ on $[0, 1]$ with 50 intervals. Set `lam` to its three smallest eigenvalues (with `np.linalg.eigvalsh`) and `exact` to $(\pi, 2\pi, 3\pi)^2$.

```python starter
import numpy as np

lam = exact = np.ones(3)
print(lam, exact)
```

```python solution
import numpy as np

n = 50
h = 1 / n
K = (np.diag([2.0] * (n - 1)) - np.diag([1.0] * (n - 2), 1) - np.diag([1.0] * (n - 2), -1)) / h**2
lam = np.linalg.eigvalsh(K)[:3]
exact = (np.pi * np.arange(1, 4))**2
print(lam, exact)
```

```python tests
import numpy as np
assert np.allclose(exact, (np.pi * np.array([1, 2, 3]))**2), "exact should be (pi, 2 pi, 3 pi) squared."
assert np.allclose(lam, 4 * 50**2 * np.sin(np.arange(1, 4) * np.pi / 100)**2), f"The grid's eigenvalues follow (4/h^2) sin^2(k pi h / 2) exactly; got {lam}."
assert np.all(lam < exact) and abs(lam[0] / exact[0] - 1) < 5e-4, "Each estimate is a little low; the first within 0.05%."
```

::: right
Right. The matrix's eigenvalues match the formula to rounding error, and the first mode is within 0.03% of $\pi^2$.
:::
:::

::: check
kind: python

## A cooling fin obeys $y'' = m^2y$ with $y(0) = 1$ (the base) and $y'(1) = 0$ (an insulated tip), with $m$ = 2. Solve it by finite differences with 100 intervals, using a ghost point $y_{n+1} = y_{n-1}$ for the tip, and set `tip` to $y(1)$.

```python starter
import numpy as np

tip = 1.0
print(tip)
```

```python solution
import numpy as np

n, m = 100, 2.0
h = 1 / n
A = np.zeros((n, n))
b = np.zeros(n)
for i in range(n):
    A[i, i] = -2 / h**2 - m * m
    if i > 0:
        A[i, i - 1] = 1 / h**2
    else:
        b[i] -= 1 / h**2
    if i < n - 1:
        A[i, i + 1] = 1 / h**2
    else:
        A[i, i - 1] += 1 / h**2
y = np.linalg.solve(A, b)
tip = y[-1]
print(tip)
```

```python tests
import math
assert abs(tip - 1 / math.cosh(2)) < 1e-4, f"The exact tip value is 1/cosh(2) = 0.26580; got {tip}."
```

::: right
Right. The ghost point makes the insulated end second-order accurate, and the tip comes out within $10^{-5}$ of $1/\cosh 2$.
:::
:::

::: explain
## Why does a finite-difference grid underestimate the high modes' eigenvalues so much more than the low ones'?

::: model
The central difference measures curvature from three points spaced $h$ apart. For a sine of wavelength much longer than $h$, three points trace the curve closely and the estimate is nearly exact. As the wavelength shrinks toward a few grid spacings, the three points sample the wave so coarsely that the curvature they see is smaller than the true curvature: the estimate becomes $\frac{4}{h^2}\sin^2\frac{k\pi h}{2}$ instead of $(k\pi)^2$, and $\sin\theta < \theta$ for every positive $\theta$. The relative error is about $\frac{(k\pi h)^2}{12}$, so it grows with the square of the mode number. Simulations of waves use ten or more points per wavelength for that reason.
:::
:::

::: practice

::: check
given: n = 4..200 int; L = 0.1..10
answer: -2*n^2/L^2
tolerance: 0.5%

## Diagonal entry for {n} intervals on $[0, \given{L}]$?

::: misses
- [any] $-2/h^2$.
:::
:::

::: check
given: N = 5..200 int; k = 1..4 int
answer: 4*N^2*sin(k*pi/(2*N))^2
tolerance: 0.5%

## Grid eigenvalue $k$ = {k} with {N} intervals on $[0, 1]$?

::: misses
- [any] $4N^2\sin^2\frac{k\pi}{2N}$.
:::
:::
:::
