---
title: "Lab: contour integrals in code"
heading: Integrating around circles, finding residues and counting zeros numerically
eyebrow: A12 · Lesson 23 · Lab: contour integrals in code
xp: 60
---

::: hook
Lessons 11 to 22 turned contour integrals into residues and residues into real integrals, inverse transforms, zero counts and causality relations. Each step can be checked numerically, and the numerics are surprisingly good: the plain trapezoid rule, applied around a circle, converges faster than any power of the step for analytic integrands. In this lab you'll build a contour integrator, use it to find residues, check a residue-theorem integral against brute force, count zeros by winding, and evaluate a Kramers–Kronig principal value.
:::

::: play
- The trapezoid rule with n points around a circle of radius r computes $\oint\frac{e^z}{z - 1}dz$. Its error falls as $2\pi e\,r^{-n}$: the farther the pole is inside the circle, relative to r, the faster.
- The curve shows that error against n for the r you choose, on a log scale. Every 10 extra points cut it by a factor $r^{10}$.
- With r = 2, 32 points already give nine correct digits.
:::

```sim plot
view: graph
x: n = 4..64
y: error = 0.0000000000000001..10 log
slider: r = 1.2..4 step 0.1 = 2
plot: 2*pi*exp(1)*r^(-n) | label: trapezoid error | samples: 200
readout: error with 32 points = 2*pi*exp(1)*r^(-32) | digits: 3
```

::: predict
## You integrate $\frac{e^z}{z - 1}$ around $\lvert z\rvert = 2$ with the trapezoid rule. Going from 16 to 32 points, roughly what happens to the error?

- [ ] It halves
- [ ] It falls by a factor of 4
- [x] It falls by a factor of about 65 000
- [ ] It doesn't change

::: reveal
It falls by about $2^{16} = 65\,536$: from $2.6 \times 10^{-4}$ to $4.0 \times 10^{-9}$. On a closed curve the trapezoid rule has no end errors, and for an analytic integrand its error falls exponentially with the number of points, at a rate set by how close the nearest singularity is to the circle.
:::
:::

::: nameit
## The trapezoid rule on a circle

On $z = c + re^{j\theta}$, $dz = jre^{j\theta}d\theta$, so with n equally spaced angles $\theta_k = 2\pi k/n$,

$$\oint f\,dz \approx \frac{2\pi}{n}\sum_{k=0}^{n-1}f(z_k)\,jre^{j\theta_k}.$$

For an integrand analytic in a ring around the circle, the error falls like $\rho^{-n}$, where ρ measures how far the nearest singularity is from the circle (here $\rho = r/1$ for a pole at 1 inside a circle of radius r). This **exponential convergence** makes contour integrals a practical numerical tool, for residues, inverse transforms and counting zeros.

## Residues and zeros by computation

A residue is $\frac{1}{2\pi j}\oint f\,dz$ around a small circle enclosing only that pole. The number of zeros minus poles inside a curve is the winding number of $f$, which you can read off by tracking $\arg f$ along the curve with its jumps of $2\pi$ removed (`np.unwrap`).

## Principal values on a grid

A midpoint grid placed symmetrically about the singular point, $\omega' = \omega + (k + \frac12)d$, pairs each point at $+u$ with one at $-u$. The large terms $\pm\frac{R(\omega)}{u}$ cancel in pairs, which is exactly what the principal value does.
:::

::: example
## How fast does the trapezoid rule converge for $\oint_{\lvert z\rvert = 2}\frac{e^z}{z - 1}dz = 2\pi je$?

::: solution
1. **Measured errors.** 6.4 with 4 points, 0.11 with 8, $2.6 \times 10^{-4}$ with 16, and $4.0 \times 10^{-9}$ with 32. The last two match $2\pi e \cdot 2^{-n}$ to three digits.
2. **Expand the integrand.** On the circle,
   $$\frac{ze^z}{z - 1} = e^z\sum_{m\ge0}z^{-m}$$
   and the coefficient of $z^{-n}$ in that product is $\sum_k\frac{1}{k!} = e$.
3. **Where the error comes from.** The n-point rule can't tell $z^{-n}$ from $z^0$ on its sample points, so it adds that term's contribution, $2\pi je\,r^{-n}$, to the answer.
4. **The rate.** Each doubling of n squares the error.

**Answer:** the error falls like $2\pi e \cdot 2^{-n}$: $2.6 \times 10^{-4}$ with 16 points and $4.0 \times 10^{-9}$ with 32.
:::
:::

::: example
## Count the zeros of $z^5 + 3z + 1$ inside $\lvert z\rvert = 1$ and $\lvert z\rvert = 2$ by computing winding numbers.

::: solution
1. **Sample and unwrap.** Sample $p(z)$ at 4000 points around each circle, take `np.unwrap(np.angle(p))`, and divide the total change by 2π.
2. **The results.** They are 1 and 5, matching the Rouché argument of lesson 21.
3. **How many samples.** The number only has to be large enough that the angle never jumps by more than π between neighbors; otherwise unwrapping can lose a turn.
4. **Zeros near the circle.** A zero very close to the circle makes the angle swing fast there, so it needs more points.

**Answer:** one zero inside $\lvert z\rvert = 1$ and five inside $\lvert z\rvert = 2$.
:::
:::

::: check
given: a = 0.5 | 1 | 2
answer: -exp(a*pi)
tolerance: 0.5%

## What is the residue of $\frac{e^{\given{a}z}}{\sin z}$ at $z = \pi$? (A numerical contour integral around a small circle should give the same.)

::: right
Right. $\frac{e^{a\pi}}{\cos\pi} = -e^{a\pi}$.
:::

::: misses
- [exp(a*pi)] $\cos\pi = -1$.
- [any] $g(\pi)/h'(\pi)$ with $h = \sin z$.
:::
:::

::: check
given: L = 10 | 100 | 1000
answer: 2/(3*L^3)
tolerance: 0.5%

## You integrate $\frac{1}{x^4 + 1}$ numerically over $[-L, L]$ with L = {L} instead of the whole line. About how much do the missing tails contribute?

::: right
Right. Each tail is about $\int_L^\infty x^{-4}dx = \frac{1}{3L^3}$, and there are two.
:::

::: misses
- [1/(3*L^3)] There are two tails.
- [any] For large x the integrand is about $x^{-4}$.
:::
:::

::: check
kind: python

## Write `contour_integral(f, c, r, n=64)` using the trapezoid rule on the circle of radius r around c (f takes NumPy arrays). Set `I` to $\oint\frac{e^z}{z - 1}dz$ around $\lvert z\rvert = 2$.

```python starter
import numpy as np

def contour_integral(f, c, r, n=64):
    return 0

I = contour_integral(lambda z: np.exp(z) / (z - 1), 0, 2)
print(I)
```

```python solution
import numpy as np

def contour_integral(f, c, r, n=64):
    t = 2 * np.pi * np.arange(n) / n
    z = c + r * np.exp(1j * t)
    return np.sum(f(z) * 1j * r * np.exp(1j * t)) * 2 * np.pi / n

I = contour_integral(lambda z: np.exp(z) / (z - 1), 0, 2)
print(I)
```

```python tests
import numpy as np
assert abs(I - 2j * np.pi * np.e) < 1e-12, f"The integral is 2*pi*j*e = 17.0795j; got {I}."
assert abs(contour_integral(lambda z: z**2, 1, 3)) < 1e-12, "An entire function integrates to zero around any circle."
```

::: right
Right. $17.0795j$ to 15 digits with 64 points.
:::
:::

::: check
kind: python

## Use a contour integral around a circle of radius 0.5 to set `res0` and `respi` to the residues of $\frac{e^z}{\sin z}$ at 0 and at π.

```python starter
import numpy as np

def contour_integral(f, c, r, n=64):
    t = 2 * np.pi * np.arange(n) / n
    z = c + r * np.exp(1j * t)
    return np.sum(f(z) * 1j * r * np.exp(1j * t)) * 2 * np.pi / n

res0 = respi = 0
print(res0, respi)
```

```python solution
import numpy as np

def contour_integral(f, c, r, n=64):
    t = 2 * np.pi * np.arange(n) / n
    z = c + r * np.exp(1j * t)
    return np.sum(f(z) * 1j * r * np.exp(1j * t)) * 2 * np.pi / n

f = lambda z: np.exp(z) / np.sin(z)
res0 = contour_integral(f, 0, 0.5) / (2j * np.pi)
respi = contour_integral(f, np.pi, 0.5) / (2j * np.pi)
print(res0, respi)
```

```python tests
import numpy as np
assert abs(res0 - 1) < 1e-10, f"At 0 the residue is e^0/cos 0 = 1; got {res0}."
assert abs(respi + np.exp(np.pi)) < 1e-8, f"At pi it is e^pi/cos(pi) = -23.14; got {respi}."
```

::: right
Right. 1 and $-e^\pi = -23.14$, as $g/h'$ predicts.
:::
:::

::: check
kind: python

## Set `by_residues` to $\int_{-\infty}^{\infty}\frac{dx}{x^4 + 1}$ from the residues $\frac{1}{4z^3}$ at the upper-half-plane roots of $z^4 + 1$ (find them with `np.roots`), and `numeric` to a trapezoid-rule value over $[-1000, 1000]$ with 2 000 001 points.

```python starter
import numpy as np

by_residues = numeric = 0.0
print(by_residues, numeric)
```

```python solution
import numpy as np

roots = np.roots([1, 0, 0, 0, 1])
upper = roots[roots.imag > 0]
by_residues = (2j * np.pi * np.sum(1 / (4 * upper**3))).real
x = np.linspace(-1000, 1000, 2000001)
y = 1 / (x**4 + 1)
h = x[1] - x[0]
numeric = h * (np.sum(y) - (y[0] + y[-1]) / 2)
print(by_residues, numeric)
```

```python tests
import numpy as np
assert abs(by_residues - np.pi / np.sqrt(2)) < 1e-12, f"The residues give pi/sqrt(2) = 2.2214; got {by_residues}."
assert abs(numeric - by_residues) < 1e-8, f"Brute force should agree to about the tails' 7e-10; got {numeric}."
```

::: right
Right. Both give 2.2214414. The brute-force value is low by $\frac{2}{3 \times 1000^3} \approx 7 \times 10^{-10}$, the missing tails.
:::
:::

::: check
kind: python

## Write `winding(f, r, n=4000)` returning the number of times $f(z)$ winds around 0 as z goes once around $\lvert z\rvert = r$. Set `w1` and `w2` for $z^5 + 3z + 1$ with r = 1 and r = 2.

```python starter
import numpy as np

def winding(f, r, n=4000):
    return 0

p = lambda z: z**5 + 3 * z + 1
w1, w2 = winding(p, 1), winding(p, 2)
print(w1, w2)
```

```python solution
import numpy as np

def winding(f, r, n=4000):
    z = r * np.exp(2j * np.pi * np.arange(n + 1) / n)
    phase = np.unwrap(np.angle(f(z)))
    return round((phase[-1] - phase[0]) / (2 * np.pi))

p = lambda z: z**5 + 3 * z + 1
w1, w2 = winding(p, 1), winding(p, 2)
print(w1, w2)
```

```python tests
assert (w1, w2) == (1, 5), f"Expect 1 zero inside the unit circle and all 5 inside radius 2; got {w1}, {w2}."
assert winding(lambda z: 1 / (z - 0.5), 1) == -1, "A pole inside counts as -1."
```

::: right
Right. 1 and 5, without solving the quintic.
:::
:::

::: check
kind: python

## Write `kk_x(R, w0)` returning $\frac1\pi\,\text{PV}\int\frac{R(\omega')}{\omega' - \omega_0}d\omega'$ on the midpoint grid $\omega' = \omega_0 + (k + \frac12)d$ with $d = 10^{-3}$ over $\lvert\omega' - \omega_0\rvert < 1000$. Set `X` to its value for $R = \frac{1}{1 + \omega^2}$ at $\omega_0 = 2$.

```python starter
import numpy as np

def kk_x(R, w0, L=1000.0, d=1e-3):
    return 0.0

X = kk_x(lambda w: 1 / (1 + w**2), 2.0)
print(X)
```

```python solution
import numpy as np

def kk_x(R, w0, L=1000.0, d=1e-3):
    k = np.arange(-int(L / d), int(L / d))
    wp = w0 + (k + 0.5) * d
    return np.sum(R(wp) / (wp - w0)) * d / np.pi

X = kk_x(lambda w: 1 / (1 + w**2), 2.0)
print(X)
```

```python tests
assert abs(X - (-0.4)) < 1e-4, f"Causality requires X(2) = -2/(1 + 4) = -0.4; got {X}."
```

::: right
Right. −0.4, the imaginary part of $\frac{1}{1 + 2j}$: the real part alone fixed it.
:::
:::

::: explain
## Why does the trapezoid rule converge so much faster around a closed circle than on an ordinary interval?

::: model
On an interval, the trapezoid rule's error comes from the ends: the Euler–Maclaurin formula expresses it through the differences of the integrand's derivatives at the two endpoints, which gives an error proportional to $h^2$. Around a closed curve the integrand is periodic, so every one of those end terms cancels, and the only error left is aliasing: the n sample points can't distinguish $e^{jn\theta}$ from a constant, so the rule adds in the Fourier coefficients at multiples of n. For an analytic integrand those coefficients fall exponentially, at a rate set by the distance to the nearest singularity, so the error falls exponentially with n.
:::
:::

::: practice

::: check
given: a = -2 | -1 | -0.5 | 0.5 | 1 | 2 | 3
answer: -exp(a*pi)
tolerance: 0.5%

## Residue of $\frac{e^{\given{a}z}}{\sin z}$ at π?

::: misses
- [any] $-e^{a\pi}$.
:::
:::

::: check
given: L = 5 | 10 | 20 | 50 | 100 | 200
answer: 2/(3*L^3)
tolerance: 0.5%

## Tail of $\int\frac{dx}{x^4 + 1}$ beyond ±{L}?

::: misses
- [any] $\frac{2}{3L^3}$.
:::
:::
:::
