---
title: "PDE lab: the heat and Laplace equations, numerically"
heading: Write the schemes, watch one blow up, and check them against exact answers
eyebrow: "A12 · Lesson 51 · PDE lab: the heat and Laplace equations, numerically"
xp: 60
---

::: hook
This lab turns lesson 48 into code. You'll write the explicit heat scheme and check it against its own amplification factor to rounding level, then push it past $r = \frac12$ and watch a millionth of a degree of noise take over. You'll fix that with Crank–Nicolson, which stays stable at any step. Finally you'll relax Laplace's equation in a square box and recover the $V_0/4$ at the center from lesson 33.
:::

::: predict
## The explicit scheme runs 60 steps at r = 0.6, starting from a smooth sine plus a wiggle of size $10^{-6}$ at the grid's finest scale. Roughly how big is the wiggle at the end?

- [ ] Still about $10^{-6}$
- [ ] Gone
- [x] About $10^{-6} \times 1.39^{60} \approx 300$
- [ ] Exactly 1

::: reveal
About 300. The finest mode's factor is $1 - 4r\sin^2(k\Delta x/2) \approx -1.39$ per step at r = 0.6, so after 60 steps it has grown by about $1.39^{60} \approx 3 \times 10^8$. The smooth sine, meanwhile, has decayed a little; the answer is all wiggle.
:::
:::

::: nameit
## What you'll write

1. `ftcs(u, r, steps)`: the explicit scheme, $u_i \leftarrow u_i + r(u_{i+1} - 2u_i + u_{i-1})$ on the interior points, with the two end values held fixed. Use NumPy slices, not a loop over i.
2. `crank_nicolson(u, r, steps)`: each step solves $\left(I - \frac r2D\right)u^{n+1} = \left(I + \frac r2D\right)u^n$ on the interior points, where D is the second-difference matrix (−2 on the diagonal, 1 beside it). Build the two matrices once and call `np.linalg.solve` each step.
3. `jacobi_box(N, iters)`: an $(N + 1) \times (N + 1)$ grid with the top row at 1 and the other edges at 0; every interior point repeatedly becomes the average of its four neighbors.

## How you'll know they're right

A grid sine $\sin(\pi x)$ on N intervals is an exact mode of both schemes, so after n steps it must be the start times $G^n$, with

$$G_{FTCS} = 1 - 4rs^2, \qquad G_{CN} = \frac{1 - 2rs^2}{1 + 2rs^2}, \qquad s = \sin\frac{\pi}{2N}$$

These match to rounding error, which is a far sharper test than comparing with the PDE's exact solution.
:::

::: example
## With N = 20 and r = 0.4, what should 100 explicit steps do to the sine mode?

::: solution
1. **The amplification factor.** Here $s = \sin(\pi/40) = 0.07846$, so
   $$\begin{aligned} G &= 1 - 4 \times 0.4 \times 0.006156 \\ &= 0.990151 \end{aligned}$$
2. **After 100 steps.**
   $$G^{100} = 0.3716$$
3. **Compare with the PDE.** Its own decay over the same time, $t = 100r/N^2 = 0.1$, is
   $$e^{-\pi^2 \times 0.1} = 0.3727$$
   so the grid adds a 0.3% error.

**Answer:** 100 steps should shrink the sine mode to 0.3716 of its start, against the PDE's 0.3727: a 0.3% error.
:::
:::

::: example
## Why does Jacobi need about $N^2$ sweeps to settle?

::: solution
1. **One sweep.** Each sweep multiplies the slowest error mode by
   $$\cos\frac{\pi}{N} \approx 1 - \frac{\pi^2}{2N^2}$$
2. **Many sweeps.** Shrinking that error by a factor $e^{-k}$ takes about
   $$\frac{2kN^2}{\pi^2}$$
   sweeps.
3. **An example.** For N = 20 and a factor of $10^{-10}$ (k = 23), that's about 1900.
4. **The fix.** That slowness is what SOR and multigrid fix.

**Answer:** each sweep shrinks the slowest error mode only by about $1 - \frac{\pi^2}{2N^2}$, so settling takes about $\frac{2kN^2}{\pi^2}$ sweeps: about 1900 for N = 20 and a factor of $10^{-10}$.
:::
:::

::: check
kind: python

## Step 1. Write `ftcs(u, r, steps)` returning the grid after `steps` explicit steps, with `u[0]` and `u[-1]` held fixed. Don't change the array you're given.

```python starter
import numpy as np

def ftcs(u, r, steps):
    u = u.copy()
    # update the interior points u[1:-1] each step
    return u

N = 20
x = np.linspace(0, 1, N + 1)
print(ftcs(np.sin(np.pi * x), 0.4, 100)[N // 2])
```

```python solution
import numpy as np

def ftcs(u, r, steps):
    u = u.copy()
    for _ in range(steps):
        u[1:-1] = u[1:-1] + r * (u[2:] - 2 * u[1:-1] + u[:-2])
    return u

N = 20
x = np.linspace(0, 1, N + 1)
print(ftcs(np.sin(np.pi * x), 0.4, 100)[N // 2])
```

```python tests
import numpy as np
N = 20
x = np.linspace(0, 1, N + 1)
u0 = np.sin(np.pi * x)
G = 1 - 4 * 0.4 * np.sin(np.pi / (2 * N)) ** 2
u = ftcs(u0, 0.4, 100)
assert np.allclose(u0, np.sin(np.pi * x)), "ftcs changed the array it was given; work on a copy."
assert np.allclose(u, G ** 100 * u0, atol=1e-12), f"After 100 steps the sine should be {G ** 100:.6f} times its start; the middle is {u[N // 2]:.6f}."
w = ftcs(u0 + 1e-6 * np.sin(19 * np.pi * x), 0.6, 60)
assert np.max(np.abs(w)) > 10, "At r = 0.6 the finest wiggle should grow by about 1.39 per step and take over."
v = ftcs(u0 + 1e-6 * np.sin(19 * np.pi * x), 0.45, 60)
assert np.max(np.abs(v)) < 1, "At r = 0.45 the scheme is stable and nothing should grow."
```

::: right
Right. The sine decays by exactly $G^{100}$, and the same tiny wiggle is harmless at r = 0.45 and ruinous at r = 0.6.
:::
:::

::: check
kind: python

## Step 2. Write `crank_nicolson(u, r, steps)` with the ends held fixed (at zero here), solving the tridiagonal system on the interior points each step.

```python starter
import numpy as np

def crank_nicolson(u, r, steps):
    u = u.copy()
    m = len(u) - 2
    # D: -2 on the diagonal, 1 beside it (size m x m)
    # A = I - r/2 D, B = I + r/2 D; each step: u[1:-1] = solve(A, B @ u[1:-1])
    return u

N = 20
x = np.linspace(0, 1, N + 1)
print(crank_nicolson(np.sin(np.pi * x), 2.0, 10)[N // 2])
```

```python solution
import numpy as np

def crank_nicolson(u, r, steps):
    u = u.copy()
    m = len(u) - 2
    D = -2 * np.eye(m) + np.eye(m, k=1) + np.eye(m, k=-1)
    A = np.eye(m) - r / 2 * D
    B = np.eye(m) + r / 2 * D
    for _ in range(steps):
        u[1:-1] = np.linalg.solve(A, B @ u[1:-1])
    return u

N = 20
x = np.linspace(0, 1, N + 1)
print(crank_nicolson(np.sin(np.pi * x), 2.0, 10)[N // 2])
```

```python tests
import numpy as np
N = 20
x = np.linspace(0, 1, N + 1)
u0 = np.sin(np.pi * x)
s2 = np.sin(np.pi / (2 * N)) ** 2
for r in (0.4, 2.0, 10.0):
    G = (1 - 2 * r * s2) / (1 + 2 * r * s2)
    u = crank_nicolson(u0, r, 10)
    assert np.allclose(u, G ** 10 * u0, atol=1e-12), f"At r = {r}, 10 steps should multiply the sine by {G ** 10:.6f}; the middle is {u[N // 2]:.6f}."
w = crank_nicolson(u0 + 1e-6 * np.sin(19 * np.pi * x), 10.0, 60)
assert np.max(np.abs(w)) < 1, "Crank-Nicolson should stay bounded even at r = 10."
```

::: right
Right. Crank–Nicolson matches its amplification factor at r = 0.4, 2 and 10, and the wiggle stays small (it flips sign each step at large r, but never grows).
:::
:::

::: check
kind: python

## Step 3. Write `jacobi_box(N, iters)`: an $(N + 1) \times (N + 1)$ grid (row 0 is the top) with the top row at 1 and the other edges at 0, relaxed `iters` times by four-neighbor averaging of the interior. Return the grid.

```python starter
import numpy as np

def jacobi_box(N, iters):
    V = np.zeros((N + 1, N + 1))
    V[0, :] = 1.0
    # each sweep: V[1:-1, 1:-1] = average of the four neighbors
    return V

V = jacobi_box(20, 2000)
print(V[10, 10])
```

```python solution
import numpy as np

def jacobi_box(N, iters):
    V = np.zeros((N + 1, N + 1))
    V[0, :] = 1.0
    for _ in range(iters):
        V[1:-1, 1:-1] = 0.25 * (V[:-2, 1:-1] + V[2:, 1:-1] + V[1:-1, :-2] + V[1:-1, 2:])
    return V

V = jacobi_box(20, 2000)
print(V[10, 10])
```

```python tests
import numpy as np
V = jacobi_box(20, 2000)
assert V.shape == (21, 21), "The grid should be (N + 1) x (N + 1)."
assert np.allclose(V[0, 1:-1], 1) and np.allclose(V[-1, :], 0) and np.allclose(V[:, -1][1:], 0), "Keep the top at 1 and the other edges at 0."
assert abs(V[10, 10] - 0.25) < 1e-6, f"The center should settle to 0.25; got {V[10, 10]:.8f}."
assert abs(V[10, 5] - V[10, 15]) < 1e-9, "The solution should be symmetric left to right."
W = jacobi_box(20, 50)
assert abs(W[10, 10] - 0.25) > 0.01, "After only 50 sweeps the center shouldn't have settled yet; are you doing exactly iters sweeps?"
```

::: right
Right. The discrete box gives 0.25 at the center exactly, for the same symmetry reason as the continuous one, and Jacobi needs a couple of thousand sweeps on a 20 × 20 grid to show it.
:::
:::

::: check
given: N = 20 | 40 | 80; k = 10 | 23
answer: 2*k*N^2/pi^2
tolerance: 1%

## About how many Jacobi sweeps does an N = {N} box need to shrink its slowest error by a factor $e^{-\given{k}}$?

::: right
Right. $\frac{2kN^2}{\pi^2}$ = {answer}.
:::

::: misses
- [k*N^2/pi^2] Each sweep multiplies the slowest mode by about $1 - \frac{\pi^2}{2N^2}$.
- [any] Not yet. Solve $\left(1 - \frac{\pi^2}{2N^2}\right)^n = e^{-k}$.
:::
:::

::: check
given: r = 1 | 5 | 20
answer: (1 - 2*r)/(1 + 2*r)
tolerance: 0.5%

## What's Crank–Nicolson's amplification factor for the finest grid mode ($k\Delta x = \pi$) at r = {r}?

::: right
Right. $\frac{1 - 2r}{1 + 2r}$ = {answer}: its size stays below 1, but it approaches −1 as r grows, so sharp features flicker and fade only slowly.
:::

::: misses
- [1 - 4*r] That's the explicit scheme's.
- [any] Not yet. $G = \frac{1 - 2r\sin^2(k\Delta x/2)}{1 + 2r\sin^2(k\Delta x/2)}$.
:::
:::

::: explain
## Why is it a stronger test to compare a scheme with its own amplification factor than with the exact solution of the PDE?

::: model
The scheme's result differs from the PDE's exact solution by the discretization error, which is small but not zero (0.3% in this lab), so a comparison with the PDE needs a loose tolerance that could hide a real bug of similar size. A sine on the grid is an exact eigenvector of the discrete scheme, so a correct implementation must multiply it by exactly $G^n$, to rounding error. Comparing at 1e-12 catches any mistake in the update, an off-by-one in the slices, a wrong sign or a boundary handled wrongly, which the looser comparison would let through.
:::
:::

::: practice

::: check
given: N = 30 | 60; k = 5 | 15
answer: 2*k*N^2/pi^2
tolerance: 1%

## Jacobi sweeps for N = {N}, factor $e^{-\given{k}}$?

::: misses
- [any] $2kN^2/\pi^2$.
:::
:::

::: check
given: r = 0.5 | 1 | 2 | 5 | 10 | 50
answer: (1 - 2*r)/(1 + 2*r)
tolerance: 0.5%

## Crank–Nicolson finest-mode factor at r = {r}?

::: misses
- [any] $\frac{1 - 2r}{1 + 2r}$.
:::
:::

::: check
given: r = 0.25 | 0.45; N = 10 | 40
answer: 1 - 4*r*sin(pi/(2*N))^2
tolerance: 0.00005

## Explicit amplification of the sine mode, r = {r}, N = {N} intervals?

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