---
title: "Lab: special functions and Green's functions in code"
heading: Bessel zeros, Legendre expansions, Green's function integrals and induced charge
eyebrow: A12 · Lesson 45 · Lab: special functions in code
xp: 60
---

::: hook
Lessons 38 to 44 leaned on tables: Bessel zeros like 2.4048, Legendre polynomials, Green's functions. In this lab you'll compute those numbers yourself. You'll sum Bessel's series and find its zeros, which give drum overtones and waveguide cutoffs. You'll build Legendre polynomials by recursion and expand a function in them. Then you'll solve a loaded string by integrating its Green's function, and check that a point charge above a grounded plane induces exactly its own charge, with the opposite sign.
:::

::: play
- The curves are $J_0(x)$ and $J_1(x)$, computed from their power series. Their zeros are where drums, fibers and waveguides have their modes.
- The power series converges for every x, but for large x its terms grow huge before they cancel. With 60 terms in double precision the series is good to about $10^{-9}$ at x = 20 and only $10^{-5}$ at x = 30.
- The readout gives the drum's first overtone ratio, $j_{11}/j_{01}$, from the zeros of these two curves.
:::

```sim plot
view: graph
x: x = 0..15
y: J = -0.5..1
plot: J0(x) | label: J₀ | samples: 500
plot: J1(x) | label: J₁ | color: ch3 | samples: 500
readout: first overtone over the fundamental = 3.831706/2.404826 | digits: 5
```

::: predict
## A drumhead's fundamental is 100 Hz. Where is its next mode, (1, 1)?

- [ ] 200 Hz
- [x] 159 Hz
- [ ] 141 Hz
- [ ] 230 Hz

::: reveal
159 Hz. Mode frequencies go as the Bessel zeros, and the (1, 1) mode uses the first zero of $J_1$, 3.8317, against $J_0$'s 2.4048: a ratio of 1.593. The next, (2, 1), is at 214 Hz and (0, 2) at 230 Hz. None of these is a whole multiple of 100 Hz.
:::
:::

::: nameit
## Series, recursions and their limits

- **Bessel functions** from $J_n(x) = \sum_k\frac{(-1)^k}{k!(k + n)!}\left(\frac x2\right)^{2k + n}$: fine for moderate x. For large x the terms reach about $e^x/\sqrt x$ before canceling, so rounding errors of $10^{-16}$ times that remain. Libraries switch to asymptotic forms there.
- **Legendre polynomials** from Bonnet's recursion $(k + 1)P_{k+1} = (2k + 1)xP_k - kP_{k-1}$: stable and exact on $[-1, 1]$.
- **Zeros** by bisection inside brackets where the function changes sign.

## Expansions

On $[-1, 1]$ the Legendre polynomials are orthogonal with $\int P_n^2\,dx = \frac{2}{2n + 1}$, so $f = \sum a_nP_n$ with $a_n = \frac{2n + 1}{2}\int_{-1}^{1}fP_n\,dx$. The same pattern, with different weights, holds for Bessel series on a disk.

## Green's functions as code

A Green's function turns a boundary-value problem into an integral: $u(x) = \int G(x, s)f(s)\,ds$. Numerically that's one quadrature per point, and it works for any load f, measured data included.
:::

::: example
## Find the first three zeros of $J_0$ from its series.

::: solution
1. **Bracket the zeros.** Tabulating $J_0$ shows sign changes in (2, 3), (5, 6) and (8, 9).
2. **Bisect.** Bisection in each, with the 60-term series, gives 2.404826, 5.520078 and 8.653728, matching the tables to all six figures.
3. **The gaps.** They are 3.115 and 3.134, approaching π: for large x,
   $$J_0(x) \approx \sqrt{\frac{2}{\pi x}}\cos\left(x - \frac\pi4\right)$$
   a slowly fading cosine.
4. **Check the approximation.** It gives the third zero as $\frac{11\pi}{4} = 8.639$, already within 0.2%.

**Answer:** the first three zeros of $J_0$ are 2.404826, 5.520078 and 8.653728.
:::
:::

::: example
## Expand $f(x) = \lvert x\rvert$ on $[-1, 1]$ in Legendre polynomials.

::: solution
1. **Only even terms.** f is even, so only even n appear, and
   $$a_n = (2n + 1)\int_0^1xP_n\,dx$$
2. **The n = 0 term.** With $P_0 = 1$: $a_0 = \frac12$.
3. **The n = 2 term.** With $P_2 = \frac{3x^2 - 1}{2}$:
   $$\begin{aligned} \int_0^1xP_2\,dx &= \frac12\left(\frac34 - \frac12\right) \\ &= \frac18 \end{aligned}$$
   so $a_2 = \frac58$.
4. **The n = 4 term.** With $P_4 = \frac{35x^4 - 30x^2 + 3}{8}$:
   $$\begin{aligned} a_4 &= 9 \times \frac18\left(\frac{35}{6} - \frac{30}{4} + \frac32\right) \\ &= -\frac{3}{16} \end{aligned}$$
5. **The expansion.**
   $$\lvert x\rvert \approx \frac12 + \frac58P_2(x) - \frac{3}{16}P_4(x)$$
6. **Check at the kink.** At x = 0 that gives
   $$\frac12 - \frac58\cdot\frac12 - \frac{3}{16}\cdot\frac38 = 0.117$$
   The error at the kink shrinks slowly as terms are added, while away from it the series converges quickly.

**Answer:** $\lvert x\rvert \approx \frac12 + \frac58P_2(x) - \frac{3}{16}P_4(x)$.
:::
:::

::: check
given: c = 50 | 100; a = 0.1 | 0.3
answer: 2.404826*c/(2*pi*a)
unit: Hz
tolerance: 0.5%

## A circular drumhead of radius {a} m has wave speed {c} m/s. What is its fundamental?

::: right
Right. $f = \frac{j_{01}c}{2\pi a}$ with $j_{01} = 2.4048$.
:::

::: misses
- [c/(2*a)] That's a string's fundamental; a circle's first mode uses the Bessel zero.
- [any] $k = j_{01}/a$ and $f = \frac{ck}{2\pi}$.
:::
:::

::: check
kind: parts
given: c = 1 | 3; d = 0 | 2

## Expand $f(x) = \given{c}x^2 + \given{d}$ on $[-1, 1]$ in Legendre polynomials.

::: part
answer: c/3 + d
tolerance: 0.5%

### What is $a_0$?

::: misses
- [d] The $x^2$ term has an average of $\frac13$ too.
- [any] $a_0$ is the average of f over $[-1, 1]$.
:::
:::

::: part
answer: 2*c/3
tolerance: 0.5%

### What is $a_2$?

::: misses
- [c] $x^2 = \frac13 + \frac23P_2$.
- [any] Write $x^2$ in terms of $P_0$ and $P_2$.
:::
:::
:::

::: check
kind: python

## Write `J(n, x)` summing 60 terms of the Bessel series and `bisect(f, a, b)`. Set `z0` to the first three zeros of $J_0$ (brackets (2, 3), (5, 6), (8, 9)) and `ratio` to the first zero of $J_1$ (bracket (3, 4.5)) over the first of $J_0$.

```python starter
import math

def J(n, x, terms=60):
    return 0.0

def bisect(f, a, b):
    return (a + b) / 2

z0 = [bisect(lambda x: J(0, x), a, b) for a, b in [(2, 3), (5, 6), (8, 9)]]
ratio = bisect(lambda x: J(1, x), 3, 4.5) / z0[0]
print(z0, ratio)
```

```python solution
import math

def J(n, x, terms=60):
    return sum((-1)**k * (x / 2)**(2 * k + n) / (math.factorial(k) * math.factorial(k + n)) for k in range(terms))

def bisect(f, a, b):
    for _ in range(100):
        m = (a + b) / 2
        if f(a) * f(m) <= 0:
            b = m
        else:
            a = m
    return (a + b) / 2

z0 = [bisect(lambda x: J(0, x), a, b) for a, b in [(2, 3), (5, 6), (8, 9)]]
ratio = bisect(lambda x: J(1, x), 3, 4.5) / z0[0]
print(z0, ratio)
```

```python tests
expected = [2.404826, 5.520078, 8.653728]
assert all(abs(a - b) < 1e-6 for a, b in zip(z0, expected)), f"Expect {expected}; got {z0}."
assert abs(ratio - 1.593340) < 1e-5, f"The drum's first overtone ratio is 3.831706/2.404826 = 1.59334; got {ratio}."
```

::: right
Right. 2.404826, 5.520078, 8.653728, and an overtone ratio of 1.59334.
:::
:::

::: check
kind: python

## Write `legendre(n, x)` using Bonnet's recursion (x may be a NumPy array). On 200 001 points of $[-1, 1]$, set `a` to the coefficients $a_0$ to $a_4$ of $\lvert x\rvert$, and `norm3` to $\int_{-1}^1P_3^2\,dx$.

```python starter
import numpy as np

def legendre(n, x):
    return x**n

x = np.linspace(-1, 1, 200001)
h = x[1] - x[0]
trap = lambda y: h * (np.sum(y) - (y[0] + y[-1]) / 2)
a = [(2 * n + 1) / 2 * trap(np.abs(x) * legendre(n, x)) for n in range(5)]
norm3 = trap(legendre(3, x)**2)
print(a, norm3)
```

```python solution
import numpy as np

def legendre(n, x):
    p0, p1 = np.ones_like(x), x
    if n == 0:
        return p0
    for k in range(1, n):
        p0, p1 = p1, ((2 * k + 1) * x * p1 - k * p0) / (k + 1)
    return p1

x = np.linspace(-1, 1, 200001)
h = x[1] - x[0]
trap = lambda y: h * (np.sum(y) - (y[0] + y[-1]) / 2)
a = [(2 * n + 1) / 2 * trap(np.abs(x) * legendre(n, x)) for n in range(5)]
norm3 = trap(legendre(3, x)**2)
print(a, norm3)
```

```python tests
expected = [0.5, 0, 0.625, 0, -0.1875]
assert all(abs(p - q) < 1e-6 for p, q in zip(a, expected)), f"Expect 1/2, 0, 5/8, 0, -3/16; got {a}."
assert abs(norm3 - 2 / 7) < 1e-8, f"The norm of P3 is 2/7; got {norm3}."
```

::: right
Right. $\frac12$, 0, $\frac58$, 0, $-\frac{3}{16}$: odd terms vanish because $\lvert x\rvert$ is even.
:::
:::

::: check
kind: python

## A string on (0, 1) satisfies $-u'' = \sin\pi x$ with fixed ends. Using $G(x, s) = x(1 - s)$ for $s \ge x$ and $s(1 - x)$ for $s < x$, set `u03` to $\int_0^1G(0.3, s)\sin\pi s\,ds$ (trapezoid rule, 100 001 points) and `exact` to $\frac{\sin 0.3\pi}{\pi^2}$.

```python starter
import numpy as np

u03 = 0.0
exact = np.sin(0.3 * np.pi) / np.pi**2
print(u03, exact)
```

```python solution
import numpy as np

s = np.linspace(0, 1, 100001)
h = s[1] - s[0]
G = np.where(s >= 0.3, 0.3 * (1 - s), s * (1 - 0.3))
y = G * np.sin(np.pi * s)
u03 = h * (np.sum(y) - (y[0] + y[-1]) / 2)
exact = np.sin(0.3 * np.pi) / np.pi**2
print(u03, exact)
```

```python tests
assert abs(u03 - exact) < 1e-8, f"The Green's function integral should give sin(0.3 pi)/pi^2 = 0.081971; got {u03}."
```

::: right
Right. 0.081971 both ways. The kink in G at s = x costs the trapezoid rule a little accuracy, but $10^{-10}$ is plenty.
:::
:::

::: check
kind: python

## A charge q = 1 sits at height h = 1 above a grounded plane, inducing $\sigma(\rho) = -\frac{qh}{2\pi(\rho^2 + h^2)^{3/2}}$. Set `total` to $\int_0^R\sigma\,2\pi\rho\,d\rho$ with $R = 10^4$, using the trapezoid rule on `np.concatenate([[0], np.logspace(-6, 4, 200001)])`, and `tail` to the charge beyond R, $-\frac{qh}{\sqrt{R^2 + h^2}}$.

```python starter
import numpy as np

total = 0.0
tail = 0.0
print(total, tail, total + tail)
```

```python solution
import numpy as np

q, h = 1.0, 1.0
rho = np.concatenate([[0], np.logspace(-6, 4, 200001)])
y = -q * h / (2 * np.pi * (rho**2 + h**2)**1.5) * 2 * np.pi * rho
total = np.sum((y[1:] + y[:-1]) / 2 * np.diff(rho))
R = rho[-1]
tail = -q * h / np.sqrt(R**2 + h**2)
print(total, tail, total + tail)
```

```python tests
assert abs(total + 0.9999) < 1e-6, f"Within 10^4 heights the plane holds -0.9999 q; got {total}."
assert abs(total + tail + 1) < 1e-6, f"With the tail added the induced charge is exactly -q; got {total + tail}."
```

::: right
Right. −0.9999 within $10^4$ heights and −1 in all: the plane holds exactly the image's charge, as Gauss's law requires.
:::
:::

::: explain
## Why does the power series for $J_0(x)$ lose accuracy at large x even though it converges for every x?

::: model
For large x the individual terms $\frac{(x/2)^{2k}}{(k!)^2}$ grow enormous before the factorials win: at x = 30 the largest is about $10^{11}$. The terms alternate in sign and cancel down to a result smaller than 1. Each term carries a relative rounding error near $10^{-16}$, so the sum inherits an absolute error of about $10^{-16}$ times the largest term, around $10^{-5}$, and no number of extra terms fixes that. The series is exact in exact arithmetic; the trouble is cancellation in floating point. Libraries therefore switch to asymptotic expansions or recurrences for large x.
:::
:::

::: practice

::: check
given: c = 30 | 200; a = 0.05 | 0.5
answer: 2.404826*c/(2*pi*a)
unit: Hz
tolerance: 0.5%

## Drum fundamental, radius {a} m, wave speed {c} m/s?

::: misses
- [any] $\frac{2.4048c}{2\pi a}$.
:::
:::

::: check
given: c = 1..12 int
answer: 2*c/3
tolerance: 0.5%

## $a_2$ for $\given{c}x^2$?

::: misses
- [any] $x^2 = \frac13 + \frac23P_2$.
:::
:::
:::
