---
title: Acoustics lab
heading: "Three computations in NumPy: listing a room's modes and checking Weyl's count, finding a string's modes from a finite-difference eigenvalue problem and measuring its second-order accuracy, and computing a piston's directivity from Bessel's integral to find its beamwidth"
eyebrow: S16 · Lesson 51 · Acoustics lab
xp: 100
---

::: hook
Acoustic design software does three things over and over: it finds resonances, it solves discretized wave equations, and it evaluates radiation patterns. In this lab you'll write a small version of each and test it against an exact answer: room modes counted one by one against Weyl's formula, a string's modes from a matrix eigenvalue problem against the exact harmonic series, and a loudspeaker's beam from a Bessel function you compute yourself.
:::

::: predict
## You find a string's modes by replacing the second derivative with the second difference on N intervals. As N doubles, how does the error of the fifth mode change?

- [ ] It halves
- [x] It falls by a factor of about 4
- [ ] It stays the same
- [ ] It falls by a factor of about 16

::: reveal
The second difference has a truncation error proportional to h² (A13), so the eigenvalues, and the mode frequencies, converge with second-order accuracy: halving the step cuts the error by four. Higher modes have shorter wavelengths, fewer points per wavelength and larger errors, about $(n\pi/N)^2/24$ in relative terms.
:::
:::

::: nameit
## Task 1: room modes

Loop over the integer triples $(n_x, n_y, n_z)$ up to the largest that could fall below $f_\max$, compute each mode's frequency from lesson 27's formula, keep those at or below $f_\max$, and sort them. Then compare the count with Weyl's estimate.

## Task 2: string modes by finite differences

With N intervals of width h = L/N and fixed ends, the interior displacements satisfy $-(y_{i-1} - 2y_i + y_{i+1})/h^2 = \lambda y_i$, a symmetric tridiagonal matrix whose eigenvalues λ are $(\omega/c)^2$. NumPy's `eigvalsh` returns them; the frequencies are $c\sqrt{\lambda}/2\pi$.

## Task 3: the piston's beam

Bessel's integral

$$J_1(x) = \frac{1}{\pi}\int_0^\pi\cos(t - x\sin t)\,dt$$

has a smooth periodic integrand, so the trapezoid rule converges extremely fast: 64 intervals give machine precision. Use it for the pattern $|2J_1(x)/x|$ (lesson 16), then bisect for the half-power angle.
:::

::: example
## What should task 1 report for the 5 × 4 × 3 m room, and for a 7.3 × 5.1 × 3.4 m room up to 500 Hz?

::: solution
1. **The small room.** Thirteen modes up to 100 Hz, starting
   $$\begin{aligned} &34.30,\ 42.88,\ 54.91, \\ &57.17,\ 66.67\ \text{Hz} \end{aligned}$$
2. **The larger room.** It has 1912 modes below 500 Hz.
3. **Weyl's estimate.** It gives 1919, within 0.4%.

**Answer:** the 5 × 4 × 3 m room has 13 modes up to 100 Hz, starting at 34.30 Hz; the larger room has 1912 modes below 500 Hz, against Weyl's 1919.
:::
:::

::: example
## What should tasks 2 and 3 report for the 0.65 m, 110 Hz string and the ka = 9.16 piston?

::: solution
1. **The string with 200 intervals.** The first and fifth modes are
   $$\begin{aligned} f_1 &= 110.002\ \text{Hz} \\ f_5 &= 549.87\ \text{Hz} \end{aligned}$$
   the fifth 0.026% low.
2. **Convergence.** With 50 and 100 intervals the fifth mode's errors are 0.41% and 0.10%, a ratio of 4.00.
3. **The Bessel function.**
   $$J_1(1) = 0.440051$$
4. **The piston's half-power angle.**
   $$\begin{aligned} \theta &= 0.1774\ \text{rad} \\ &= 10.16^\circ \end{aligned}$$
   matching $\sin^{-1}(1.6163/ka)$.

**Answer:** with 200 intervals the string's first mode is 110.002 Hz and its fifth 549.87 Hz, and the error falls by 4.00 each time the step halves; J₁(1) = 0.440051, and the half-power angle is 0.1774 rad (10.16°).
:::
:::

::: check
kind: python

## Step 1. Write `room_modes` and `weyl`: count a room's modes two ways.

```python starter
import numpy as np

def room_modes(Lx, Ly, Lz, fmax, c=343.0):
    # Return a sorted array of every mode frequency of a rigid rectangular room at or below
    # fmax, from f = (c/2) sqrt((nx/Lx)^2 + (ny/Ly)^2 + (nz/Lz)^2), excluding (0, 0, 0).
    return np.array([])

def weyl(V, S, L, f, c=343.0):
    # Weyl's estimate of the number of modes below f, with volume V, surface S, edge length L.
    return 0.0

m = room_modes(5, 4, 3, 100)
print(len(m), m[:5])
```

```python solution
import numpy as np

def room_modes(Lx, Ly, Lz, fmax, c=343.0):
    out = []
    nmax = [int(2*fmax*L/c) + 1 for L in (Lx, Ly, Lz)]
    for nx in range(nmax[0] + 1):
        for ny in range(nmax[1] + 1):
            for nz in range(nmax[2] + 1):
                if nx == ny == nz == 0:
                    continue
                f = c/2*np.sqrt((nx/Lx)**2 + (ny/Ly)**2 + (nz/Lz)**2)
                if f <= fmax:
                    out.append(f)
    return np.sort(np.array(out))

def weyl(V, S, L, f, c=343.0):
    return 4*np.pi*V*f**3/(3*c**3) + np.pi*S*f**2/(4*c**2) + L*f/(8*c)

m = room_modes(5, 4, 3, 100)
print(len(m), m[:5])
```

```python tests
m = np.asarray(room_modes(5, 4, 3, 100))
assert len(m) == 13, f"A 5 x 4 x 3 m room has 13 modes up to 100 Hz; you found {len(m)}."
assert np.allclose(m[:4], [34.3, 42.875, 54.9068, 57.1667], atol=1e-3), f"The lowest modes should be 34.30, 42.88, 54.91 and 57.17 Hz; got {np.round(m[:4], 3)}."
assert np.all(np.diff(m) >= 0), "Return the frequencies in increasing order."
dims = (7.3, 5.1, 3.4)
V = dims[0]*dims[1]*dims[2]; S = 2*(dims[0]*dims[1] + dims[1]*dims[2] + dims[0]*dims[2]); L = 4*sum(dims)
n = len(room_modes(*dims, 500))
w = weyl(V, S, L, 500)
assert abs(n/w - 1) < 0.03, f"At 500 Hz Weyl's estimate ({w:.0f}) should be within 3% of the exact count; your count is {n}."
```

::: right
Right. Your mode list matches the exact frequencies, and Weyl's formula predicts the count to within a fraction of a percent at 500 Hz.
:::
:::

::: check
kind: python

## Step 2. Write `string_modes`: a string's resonances from a finite-difference eigenvalue problem.

```python starter
import numpy as np

def string_modes(N, L, T, mu, k=5):
    # Divide a string fixed at both ends into N equal intervals (N - 1 interior points).
    # The second difference -(y[i-1] - 2y[i] + y[i+1])/h^2 = lambda * y[i] gives a tridiagonal
    # eigenvalue problem; each eigenvalue lambda is (omega/c)^2 with c = sqrt(T/mu).
    # Return the k lowest mode frequencies in Hz, in increasing order.
    return np.zeros(k)

print(string_modes(100, 0.65, 122.7, 0.006))
```

```python solution
import numpy as np

def string_modes(N, L, T, mu, k=5):
    h = L/N
    A = (np.diag(2*np.ones(N - 1)) - np.diag(np.ones(N - 2), 1) - np.diag(np.ones(N - 2), -1))/h**2
    lam = np.sort(np.linalg.eigvalsh(A))[:k]
    c = np.sqrt(T/mu)
    return c*np.sqrt(lam)/(2*np.pi)

print(string_modes(100, 0.65, 122.7, 0.006))
```

```python tests
L, T, mu = 0.65, 122.7, 0.006
c = np.sqrt(T/mu)
exact = np.arange(1, 6)*c/(2*L)
f = np.asarray(string_modes(200, L, T, mu))
assert len(f) == 5 and np.all(np.abs(f/exact - 1) < 5e-4), f"With 200 intervals the first five modes should be within 0.05% of {np.round(exact, 2)} Hz; got {np.round(f, 2)}."
e1 = abs(string_modes(50, L, T, mu)[4]/exact[4] - 1)
e2 = abs(string_modes(100, L, T, mu)[4]/exact[4] - 1)
assert 3.6 < e1/e2 < 4.4, f"Halving the step should cut the fifth mode's error by about 4 (second order); the ratio is {e1/e2:.2f}."
assert np.all(f < exact), "The discrete string's modes should lie slightly below the exact ones."
```

::: right
Right. Your discrete string reproduces the harmonic series, just below it, with the error falling fourfold each time the step halves.
:::
:::

::: check
kind: python

## Step 3. Write `J1`, `directivity` and `half_power_angle`: a piston's beam from Bessel's integral.

```python starter
import numpy as np

def J1(x, n=64):
    # Bessel's integral: J1(x) = (1/pi) * integral from 0 to pi of cos(t - x sin t) dt.
    # Evaluate it with the trapezoid rule on n intervals.
    return 0.0

def directivity(ka, theta):
    # Baffled piston pattern |2 J1(x)/x| with x = ka sin(theta); 1 on the axis.
    return 1.0

def half_power_angle(ka):
    # The angle (radians) where directivity falls to 1/sqrt(2), found by bisection on [0, pi/2].
    return 0.0

print(J1(1.0), directivity(9.16, 0.3), half_power_angle(9.16))
```

```python solution
import numpy as np

def J1(x, n=64):
    t = np.linspace(0, np.pi, n + 1)
    y = np.cos(t - x*np.sin(t))
    return (np.sum(y) - 0.5*(y[0] + y[-1]))*(np.pi/n)/np.pi

def directivity(ka, theta):
    x = ka*np.sin(theta)
    if abs(x) < 1e-12:
        return 1.0
    return abs(2*J1(x)/x)

def half_power_angle(ka):
    lo, hi = 0.0, np.pi/2
    for _ in range(80):
        mid = 0.5*(lo + hi)
        if directivity(ka, mid) > 1/np.sqrt(2):
            lo = mid
        else:
            hi = mid
    return 0.5*(lo + hi)

print(J1(1.0), directivity(9.16, 0.3), half_power_angle(9.16))
```

```python tests
assert abs(J1(1.0) - 0.4400505857449335) < 1e-12 and abs(J1(5.0) + 0.3275791375914652) < 1e-12, f"J1(1) = 0.44005058574 and J1(5) = -0.32757913759; got {J1(1.0)}, {J1(5.0)}."
assert abs(J1(3.8317059702075125)) < 1e-12, "J1 should vanish at its first zero, 3.83171."
assert abs(directivity(9.16, 0.0) - 1) < 1e-12, "The pattern is 1 on the axis."
x = 1.6163399
for ka in (3.0, 9.16, 20.0):
    th = half_power_angle(ka)
    assert abs(th - np.arcsin(x/ka)) < 1e-5, f"For ka = {ka} the half-power angle should be {np.degrees(np.arcsin(x/ka)):.4f} degrees; got {np.degrees(th):.4f}."
```

::: right
Right. Your Bessel function is accurate to machine precision, and the beamwidth matches the half-power point of $2J_1(x)/x$.
:::
:::

::: explain
## Why does the trapezoid rule give Bessel's integral to machine precision with so few points?

::: model
The integrand of Bessel's integral is a smooth, periodic function of t over a full period of its extension, and for periodic analytic functions the trapezoid rule's error doesn't fall as a power of the step but exponentially: the errors from the two ends of each interval cancel term by term in the Euler–Maclaurin expansion, because every derivative matches at the ends. In effect the rule integrates exactly every Fourier component up to the number of points, and the integrand's Fourier coefficients decay faster than any power. A few dozen points therefore give sixteen digits, while a non-periodic integrand would need thousands for the same accuracy.
:::
:::

::: practice

::: check
given: x = 4 | 6 | 10; y = 3 | 5; z = 2.5 | 3; a = 1 | 2; b = 0 | 1; d = 0 | 1
answer: 343/2*sqrt((a/x)^2 + (b/y)^2 + (d/z)^2)
unit: Hz
tolerance: 0.5%

## Mode ({a}, {b}, {d}) of a {x} × {y} × {z} m room?

::: misses
- [any] $\frac{c}{2}\sqrt{\sum(n/L)^2}$.
:::
:::

::: check
given: n = 1 | 3 | 5; N = 50 | 100 | 400
answer: (n*pi/N)^2/24*100
tolerance: 0.5%

## About what relative error, in percent, does the second difference give mode {n} of a string with {N} intervals?

::: misses
- [any] $(n\pi/N)^2/24$.
:::
:::

::: check
given: k = 2 | 5 | 15
answer: asin(1.6163/k)*180/pi
unit: °
tolerance: 0.5%

## Half-power half-angle of a piston with ka = {k}?

::: misses
- [any] $\sin^{-1}(1.6163/ka)$.
:::
:::
:::
