---
title: "Lab: separation of variables in code"
heading: Summing series solutions, finding eigenvalues and checking orthogonality
eyebrow: A12 · Lesson 36 · Lab: separation of variables in code
xp: 60
---

::: hook
Lessons 28 to 35 solved the heat, wave and Laplace equations as series of eigenfunctions. On paper the series are exact; in practice you sum a finite number of terms, and the eigenvalues often come from equations like $\tan k = -k/h$ that have no closed form. This lab turns the series into working code. You'll compute Fourier coefficients numerically, sum a heat series and solve it for a time, evaluate a Laplace series without overflowing, find Robin eigenvalues by bisection, and check that their eigenfunctions are orthogonal as Sturm–Liouville theory promises.
:::

::: play
- The curve is the partial sum of the sine series of a uniform starting temperature, $\frac4\pi\sum\frac{\sin n\pi x}{n}$ over odd n, after heat has flowed for a time t (in units of $L^2/\alpha$): each term is multiplied by $e^{-n^2\pi^2t}$.
- At t = 0 the partial sum overshoots near the ends, by about 9% of the jump, however many terms you keep: that's the Gibbs phenomenon.
- Raise t a little. The high terms die first, the overshoot vanishes, and three or four terms describe the profile well.
:::

```sim plot
view: graph
x: x = 0..1
y: u = -0.2..1.3
slider: t = 0..0.1 step 0.001 = 0
plot: (4/pi)*(sin(pi*x)*exp(-pi^2*t) + sin(3*pi*x)/3*exp(-9*pi^2*t) + sin(5*pi*x)/5*exp(-25*pi^2*t) + sin(7*pi*x)/7*exp(-49*pi^2*t) + sin(9*pi*x)/9*exp(-81*pi^2*t) + sin(11*pi*x)/11*exp(-121*pi^2*t) + sin(13*pi*x)/13*exp(-169*pi^2*t) + sin(15*pi*x)/15*exp(-225*pi^2*t)) | label: eight terms | samples: 800
readout: size of the third term next to the first = exp(-8*pi^2*t)/3 | digits: 4
```

::: predict
## A rod with ends at 0 starts at a uniform temperature 1. At what time, in units of $L^2/\alpha$, has its midpoint fallen to ½?

- [ ] 0.5
- [ ] 0.0253
- [x] 0.0947
- [ ] 0.693

::: reveal
0.0947. The first term alone gives $\frac4\pi e^{-\pi^2t} = \frac12$, so $t = \frac{\ln(8/\pi)}{\pi^2} = 0.09471$; the full series moves that by only $2 \times 10^{-5}$, because by then the n = 3 term has shrunk by $e^{-8\pi^2t} \approx 6 \times 10^{-4}$ relative to the first.
:::
:::

::: nameit
## Numerical coefficients

A coefficient like $b_n = \frac2L\int_0^Lf(x)\sin\frac{n\pi x}{L}dx$ can be computed with the trapezoid rule on a fine grid. Check the code on a case with a known answer (for $f = 1$, $b_n = \frac{4}{n\pi}$ for odd n) before trusting it on data.

## How many terms

For heat problems, term n carries a factor $e^{-n^2t/\tau_1}$, so after even a modest fraction of $\tau_1$ a handful of terms suffice. At t = 0 the series converges slowly (terms fall as $1/n$ for a jump), and partial sums overshoot by 8.9% of the jump near it.

## Avoiding overflow

Laplace series contain ratios like $\frac{\sinh(n\pi y/a)}{\sinh(n\pi b/a)}$. For n of a few hundred, each sinh overflows a double, though the ratio is fine. Rewrite before computing, for example $\frac{\sinh(x/2)}{\sinh x} = \frac{1}{2\cosh(x/2)}$, or use $e^{-n\pi(b - y)/a}$ for large n.

## Eigenvalues without closed forms

With a Robin end, $X(0) = 0$ and $X'(1) + hX(1) = 0$, the eigenfunctions are $\sin kx$ with $k\cos k + h\sin k = 0$. Each root lies in a known interval, $\left((n - \frac12)\pi, n\pi\right)$, where the function changes sign, so bisection finds it reliably.
:::

::: example
## How many terms of the midpoint heat series are needed for 1% accuracy at t = 0.01 (units of $L^2/\alpha$)?

::: solution
1. **The terms.** At the midpoint the terms are $\pm\frac{4}{n\pi}e^{-n^2\pi^2t}$ for odd n. At t = 0.01 they are 1.154, 0.175, 0.0216, 0.0014 for n = 1, 3, 5, 7.
2. **Bound the error.** The series alternates and its terms shrink, so the error after stopping is less than the first term left out.
3. **Where to stop.** Stopping after n = 5 leaves an error below 0.0014, well within 1% of the midpoint value of about 1.0.
4. **Compare with t = 0.** At t = 0, you'd need hundreds of terms for the same accuracy near the ends.

**Answer:** three terms (n = 1, 3 and 5) are enough.
:::
:::

::: example
## Find the lowest eigenvalue for $X'' + \lambda X = 0$ with $X(0) = 0$ and $X'(1) + X(1) = 0$.

::: solution
1. **The equation for k.** With $X = \sin kx$ the right end gives $g(k) = 0$, where
   $$g(k) = k\cos k + \sin k$$
2. **Bracket a root.** At $k = \pi/2$, $g = 1 > 0$, and at $k = \pi$, $g = -\pi < 0$, so a root lies between.
3. **Bisect.** Sixty bisection steps narrow the bracket to rounding:
   $$\begin{aligned} k_1 &= 2.02876 \\ \lambda_1 &= k_1^2 \\ &= 4.1159 \end{aligned}$$
4. **Check.** That lies between the insulated-end value $(\pi/2)^2 = 2.47$ and the fixed-end value $\pi^2 = 9.87$, as it should: a convective end lets some heat out but not as freely as a fixed temperature.
5. **The next root.** It lies between $3\pi/2$ and $2\pi$: $k_2 = 4.91318$.

**Answer:** $\lambda_1 = 4.1159$, with $k_1 = 2.02876$.
:::
:::

::: check
given: J = 1 | 2 | 10
answer: 0.08949*J
tolerance: 0.5%

## A Fourier series of a signal with a jump of {J} is cut off after many terms. By how much does the partial sum overshoot the jump's high side?

::: right
Right. About 8.95% of the jump, however many terms you keep: the Gibbs phenomenon.
:::

::: misses
- [0.179*J] That's relative to half the jump; as a fraction of the whole jump it's 8.95%.
- [any] The overshoot is $\left(\frac1\pi\text{Si}(\pi) - \frac12\right)J \approx 0.0895J$.
:::
:::

::: check
given: t = 0.005 | 0.01 | 0.05
answer: exp(-8*pi^2*t)/3
tolerance: 0.5%

## In the heat series of a uniformly started rod, how large is the n = 3 term next to the n = 1 term at time t = {t} (units of $L^2/\alpha$)?

::: right
Right. $\frac13e^{-8\pi^2t}$: the $\frac13$ from the coefficients and $e^{-(9 - 1)\pi^2t}$ from the decay rates.
:::

::: misses
- [exp(-9*pi^2*t)/3] Compare the decays: the ratio has $e^{-(9 - 1)\pi^2t}$.
- [any] $\frac{b_3}{b_1}e^{-(9 - 1)\pi^2t}$.
:::
:::

::: check
kind: python

## Write `sine_coeff(f, n)` computing $b_n = 2\int_0^1f(x)\sin n\pi x\,dx$ with the trapezoid rule on 20 001 points. Set `b` to the list of $b_1$ to $b_5$ for $f = 1$.

```python starter
import numpy as np

x = np.linspace(0, 1, 20001)

def sine_coeff(f, n):
    return 0.0

b = [sine_coeff(lambda x: np.ones_like(x), n) for n in range(1, 6)]
print(b)
```

```python solution
import numpy as np

x = np.linspace(0, 1, 20001)
h = x[1] - x[0]

def trap(y):
    return h * (np.sum(y) - (y[0] + y[-1]) / 2)

def sine_coeff(f, n):
    return 2 * trap(f(x) * np.sin(n * np.pi * x))

b = [sine_coeff(lambda x: np.ones_like(x), n) for n in range(1, 6)]
print(b)
```

```python tests
import math
expected = [4 / (n * math.pi) if n % 2 else 0 for n in range(1, 6)]
assert all(abs(a - e) < 1e-6 for a, e in zip(b, expected)), f"Expect 4/(n*pi) for odd n and 0 for even n; got {b}."
assert abs(sine_coeff(lambda x: np.sin(3 * np.pi * x), 3) - 1) < 1e-6, "A pure mode should give a coefficient of 1."
```

::: right
Right. 1.2732, 0, 0.4244, 0, 0.2546, each to about $10^{-9}$.
:::
:::

::: check
kind: python

## Write `u_mid(t, N=50)`, the midpoint temperature of a rod ($L = \alpha = 1$) that starts at 1 with ends at 0, summed over odd n below N. Find by bisection the time `t_half` when it reaches ½, and set `t_one` to the one-term answer $\frac{\ln(8/\pi)}{\pi^2}$.

```python starter
import math

def u_mid(t, N=50):
    return 1.0

t_half = 0.0
t_one = math.log(8 / math.pi) / math.pi**2
print(t_half, t_one)
```

```python solution
import math

def u_mid(t, N=50):
    return sum(4 / (n * math.pi) * math.sin(n * math.pi / 2) * math.exp(-n * n * math.pi**2 * t) for n in range(1, N, 2))

lo, hi = 0.0, 1.0
for _ in range(60):
    mid = (lo + hi) / 2
    if u_mid(mid) > 0.5:
        lo = mid
    else:
        hi = mid
t_half = (lo + hi) / 2
t_one = math.log(8 / math.pi) / math.pi**2
print(t_half, t_one)
```

```python tests
assert abs(u_mid(0.2) - 4 / math.pi * math.exp(-0.2 * math.pi**2)) < 1e-6, "By t = 0.2 the first term should dominate."
assert abs(t_half - 0.0946870) < 1e-6, f"The midpoint reaches 1/2 at t = 0.094687; got {t_half}."
assert abs(t_half - t_one) < 1e-4, "The one-term estimate should be within about 2e-5."
```

::: right
Right. 0.094687 from the series and 0.094706 from one term: the higher modes barely matter by then.
:::
:::

::: check
kind: python

## A square box has its lid at 1 and its other sides at 0. Set `center` to the series value at its center, $\sum_{n\text{ odd}}\frac{4}{n\pi}\sin\frac{n\pi}{2}\cdot\frac{\sinh(n\pi/2)}{\sinh n\pi}$, using the first 200 odd terms. Write the ratio of sinhs so that it can't overflow.

```python starter
import math

center = sum(4 / (n * math.pi) * math.sin(n * math.pi / 2) * math.sinh(n * math.pi / 2) / math.sinh(n * math.pi) for n in range(1, 401, 2))
print(center)
```

```python solution
import math

center = sum(4 / (n * math.pi) * math.sin(n * math.pi / 2) / (2 * math.cosh(n * math.pi / 2)) for n in range(1, 401, 2))
print(center)
```

```python tests
assert abs(center - 0.25) < 1e-12, f"By symmetry the center is the average of the four sides, 1/4; got {center}."
```

::: right
Right. 0.25 to rounding error. Written as two sinhs, the terms beyond n = 226 overflow a double. Each side contributes a quarter by symmetry, which makes this a good test of the code.
:::
:::

::: check
kind: python

## Write `robin_roots(h)` returning the first two positive roots of $k\cos k + h\sin k = 0$, found by bisection on $(\pi/2, \pi)$ and $(3\pi/2, 2\pi)$. Set `k1, k2 = robin_roots(1.0)`.

```python starter
import math

def robin_roots(h):
    return math.pi / 2, 3 * math.pi / 2

k1, k2 = robin_roots(1.0)
print(k1, k2)
```

```python solution
import math

def robin_roots(h):
    g = lambda k: k * math.cos(k) + h * math.sin(k)
    roots = []
    for a, b in [(math.pi / 2, math.pi), (3 * math.pi / 2, 2 * math.pi)]:
        for _ in range(100):
            m = (a + b) / 2
            if g(a) * g(m) <= 0:
                b = m
            else:
                a = m
        roots.append((a + b) / 2)
    return tuple(roots)

k1, k2 = robin_roots(1.0)
print(k1, k2)
```

```python tests
assert abs(k1 - 2.028758) < 1e-6 and abs(k2 - 4.913180) < 1e-6, f"Expect 2.028758 and 4.913180; got {k1}, {k2}."
big = robin_roots(1e6)[0]
assert abs(big - math.pi) < 1e-4, f"A huge h makes the end nearly fixed, so k1 approaches pi; got {big}."
```

::: right
Right. $k_1 = 2.02876$ and $k_2 = 4.91318$, and as h grows the end behaves like a fixed one.
:::
:::

::: check
kind: python

## Sturm–Liouville theory says the Robin eigenfunctions $\sin k_1x$ and $\sin k_2x$ are orthogonal on (0, 1). Set `overlap` to $\int_0^1\sin k_1x\sin k_2x\,dx$ (trapezoid rule, 20 001 points) with $k_1 = 2.028758$ and $k_2 = 4.913180$, and `norm1` to $\int_0^1\sin^2k_1x\,dx$.

```python starter
import numpy as np

k1, k2 = 2.028757838110434, 4.913180439434884
overlap = norm1 = 1.0
print(overlap, norm1)
```

```python solution
import numpy as np

k1, k2 = 2.028757838110434, 4.913180439434884
x = np.linspace(0, 1, 20001)
h = x[1] - x[0]

def trap(y):
    return h * (np.sum(y) - (y[0] + y[-1]) / 2)

overlap = trap(np.sin(k1 * x) * np.sin(k2 * x))
norm1 = trap(np.sin(k1 * x)**2)
print(overlap, norm1)
```

```python tests
assert abs(overlap) < 1e-6, f"The eigenfunctions should be orthogonal; got {overlap}."
assert abs(norm1 - (0.5 - np.sin(2 * k1) / (4 * k1))) < 1e-8, f"The norm is 1/2 - sin(2k)/(4k); got {norm1}."
```

::: right
Right. The overlap is zero to the accuracy of the quadrature, though these sines aren't the usual Fourier ones: orthogonality comes from the equation and its boundary conditions.
:::
:::

::: explain
## Why do partial sums of a Fourier series overshoot near a jump, and why does the heat equation remove the overshoot?

::: model
A partial sum with N terms is the true function smoothed by the Dirichlet kernel, a narrow oscillating bump whose width shrinks as $1/N$ and which has negative side lobes. Near a jump, sliding that kernel across the step gives a ripple whose largest peak overshoots by about 9% of the jump; adding terms squeezes the ripple closer to the jump but doesn't lower its peak. The heat equation multiplies term n by $e^{-n^2\pi^2t}$, which smooths the coefficients' sharp cutoff into a gentle roll-off. Smoothing a step with a positive kernel can't overshoot, so once the high terms have decayed the ripple is gone.
:::
:::

::: practice

::: check
given: J = 0.5 | 1 | 2 | 4 | 5 | 10
answer: 0.08949*J
tolerance: 0.5%

## Gibbs overshoot for a jump of {J}?

::: misses
- [any] About 8.95% of the jump.
:::
:::

::: check
given: t = 0.001 | 0.002 | 0.005 | 0.01 | 0.02 | 0.05
answer: exp(-8*pi^2*t)/3
tolerance: 0.5%

## Ratio of the n = 3 term to n = 1 at t = {t}?

::: misses
- [any] $\frac13e^{-8\pi^2t}$.
:::
:::
:::
