---
title: "Lab: complex functions in code"
heading: Checking analyticity, branches, roots and maps numerically
eyebrow: A12 · Lesson 9 · Lab: complex functions in code
xp: 60
---

::: hook
Lessons 1 to 8 built up the complex derivative, the Cauchy–Riemann equations, branches of the logarithm, roots and bilinear maps. Python works with complex numbers directly (`1 + 2j`, with `cmath` for functions), so each of those ideas can be tested by computation. In this lab you'll take derivatives in two directions to see analyticity hold and fail, pick branches of the logarithm, place a filter's poles as roots, check the Smith chart's circles to rounding error, and measure how a conformal map stretches area.
:::

::: play
- A central difference $\frac{f(z + h) - f(z - h)}{2h}$ has an error that shrinks as $h^2$. For $f = z^3$ the error is exactly $h^2$.
- The curve shows that error against h on log axes, together with rounding error, which grows as $\varepsilon/h$ with $\varepsilon \approx 10^{-16}$.
- The two meet near $h = 10^{-5}$, where the total error is smallest. That's the step the lab uses.
:::

```sim plot
view: graph
x: h = 0.000000001..0.1 log
y: error = 0.0000000000000001..0.01 log
plot: h^2 | label: truncation error
plot: 1e-16/h | label: rounding error | color: ch3
plot: h^2 + 1e-16/h | label: total | color: ch2 | dashed
```

::: predict
## You estimate the derivative of $\bar z$ at a point once by stepping along the real axis and once by stepping along the imaginary axis. What do you get?

- [ ] The same number both times
- [x] 1 along the real axis and −1 along the imaginary axis
- [ ] 0 both times
- [ ] Two numbers that depend on the point

::: reveal
1 and −1. Along the real axis, $\overline{z + h} - \bar z = h$, so the quotient is 1. Along the imaginary axis, $\overline{z + jh} - \bar z = -jh$, and dividing by $jh$ gives −1. A complex derivative must not depend on the direction, so $\bar z$ has none, anywhere.
:::
:::

::: nameit
## Complex numbers in Python

Write $j$ as `1j`. `abs(z)` is the size, `cmath.phase(z)` the principal angle in $(-\pi, \pi]$, `z.conjugate()` the conjugate, and `cmath.exp`, `cmath.log` and `cmath.sqrt` the principal-branch functions. NumPy arrays of complex numbers work the same way, element by element.

## Testing analyticity numerically

Take central differences along x and along y: $\frac{f(z + h) - f(z - h)}{2h}$ and $\frac{f(z + jh) - f(z - jh)}{2jh}$. For an analytic f both approach $f'(z)$, and their difference is about $h^2$. For a non-analytic f they differ by a fixed amount however small h gets.

## Checking a map

To test a claim like "this line maps onto that circle", map many points along the line and compute the largest distance from the circle. A correct claim leaves only rounding error, around $10^{-15}$; a wrong one leaves a visible gap.
:::

::: example
## Find the poles of a fourth-order Butterworth filter with $\omega_c = 1$ numerically.

::: solution
1. **The equation.** The poles are the left-half-plane roots of
   $$s^8 = -1$$
2. **Find them in code.** Compute all eight roots with `r = [cmath.exp(1j*(math.pi + 2*math.pi*k)/8) for k in range(8)]`, then keep those with negative real part.
3. **The four poles.**
   $$\begin{aligned} &-0.3827 \pm 0.9239j \\ &-0.9239 \pm 0.3827j \end{aligned}$$
   at angles of 112.5° and 157.5° and their mirror images.
4. **Multiply out the pairs.**
   $$\begin{aligned} &(s^2 + 0.7654s + 1) \\ &\times (s^2 + 1.8478s + 1) \end{aligned}$$
   gives the familiar Butterworth polynomial; the coefficients $2\cos 67.5°$ and $2\cos 22.5°$ come straight from the pole angles.

**Answer:** the poles are $-0.3827 \pm 0.9239j$ and $-0.9239 \pm 0.3827j$, at angles of 112.5° and 157.5° and their mirror images.
:::
:::

::: example
## Check numerically that $w = 1/z$ maps the line $\text{Re}\,z = \frac12$ onto the circle $\lvert w - 1\rvert = 1$.

::: solution
1. **Map a long stretch of the line.** `y = np.linspace(-100, 100, 4001)`, then `w = 1/(0.5 + 1j*y)`.
2. **Measure the worst miss.** `np.max(np.abs(np.abs(w - 1) - 1))` comes out about $2 \times 10^{-16}$: every mapped point lies on the circle to rounding error.
3. **A control.** Test against the wrong circle $\lvert w - 1\rvert = 0.9$: the largest gap is then 0.1.
4. **Why bother.** Numerical checks like this catch sign slips and wrong centers quickly, before they reach a design.

**Answer:** every mapped point is within about $2 \times 10^{-16}$ of the circle $\lvert w - 1\rvert = 1$, which is rounding error.
:::
:::

::: check
given: h = 0.01 | 0.001 | 0.1
answer: h^2
tolerance: 0.5%

## For $f = z^3$, the central difference $\frac{f(z + h) - f(z - h)}{2h}$ equals $3z^2 + h^2$ exactly. What is its error with h = {h}?

::: right
Right. $h^2$, whatever z is: the $z^3$ terms' expansion leaves exactly $h^2$ over.
:::

::: misses
- [h] Central differences are second order: the error goes as $h^2$.
- [any] Expand $(z \pm h)^3$ and subtract.
:::
:::

::: check
given: a = 1 | 2; b = 1 | 3
answer: 4*(a^2 + b^2)
tolerance: 0.5%

## $f(z) = z^2$ maps a tiny square near $z_0 = \given{a} + \given{b}j$. By what factor does the square's area grow?

::: right
Right. $\lvert f'\rvert^2 = \lvert 2z_0\rvert^2 = 4(a^2 + b^2)$: lengths stretch by $\lvert f'\rvert$ in every direction.
:::

::: misses
- [2*sqrt(a^2 + b^2)] That's the length factor; area goes as its square.
- [any] $\lvert f'(z_0)\rvert^2$.
:::
:::

::: check
kind: python

## Write `deriv_x(f, z, h)` and `deriv_y(f, z, h)`, central differences stepping along the real and imaginary directions. With h = 1e-5, set `a_x`, `a_y` for $f = z^3$ at $z_0 = 1 + 2j$, and `b_x`, `b_y` for $f = \bar z$ there.

```python starter
def deriv_x(f, z, h=1e-5):
    return 0

def deriv_y(f, z, h=1e-5):
    return 0

z0 = 1 + 2j
a_x, a_y = deriv_x(lambda z: z**3, z0), deriv_y(lambda z: z**3, z0)
b_x, b_y = deriv_x(lambda z: z.conjugate(), z0), deriv_y(lambda z: z.conjugate(), z0)
print(a_x, a_y, b_x, b_y)
```

```python solution
def deriv_x(f, z, h=1e-5):
    return (f(z + h) - f(z - h)) / (2 * h)

def deriv_y(f, z, h=1e-5):
    return (f(z + 1j * h) - f(z - 1j * h)) / (2j * h)

z0 = 1 + 2j
a_x, a_y = deriv_x(lambda z: z**3, z0), deriv_y(lambda z: z**3, z0)
b_x, b_y = deriv_x(lambda z: z.conjugate(), z0), deriv_y(lambda z: z.conjugate(), z0)
print(a_x, a_y, b_x, b_y)
```

```python tests
assert abs(a_x - (-9 + 12j)) < 1e-6, f"The derivative of z^3 is 3z^2 = -9 + 12j; got {a_x}."
assert abs(a_y - a_x) < 1e-6, f"An analytic function gives the same derivative in every direction; got {a_x} and {a_y}."
assert abs(b_x - 1) < 1e-9 and abs(b_y + 1) < 1e-9, f"For the conjugate, expect 1 along x and -1 along y; got {b_x}, {b_y}."
```

::: right
Right. $z^3$ gives $-9 + 12j$ both ways; $\bar z$ gives 1 and −1, so it has no complex derivative.
:::
:::

::: check
kind: python

## Write `log_branch(z, k)` returning $\ln\lvert z\rvert + j(\text{Arg}\,z + 2\pi k)$. Use it to set `jj0` to $j^j$ on the principal branch and `jj1` on the branch k = 1, both as $e^{j\log j}$.

```python starter
import cmath, math

def log_branch(z, k):
    return 0

jj0 = cmath.exp(1j * log_branch(1j, 0))
jj1 = cmath.exp(1j * log_branch(1j, 1))
print(jj0, jj1)
```

```python solution
import cmath, math

def log_branch(z, k):
    return math.log(abs(z)) + 1j * (cmath.phase(z) + 2 * math.pi * k)

jj0 = cmath.exp(1j * log_branch(1j, 0))
jj1 = cmath.exp(1j * log_branch(1j, 1))
print(jj0, jj1)
```

```python tests
import math
assert abs(log_branch(-1, 0) - math.pi * 1j) < 1e-15, "The principal log of -1 is j*pi."
assert abs(jj0 - math.exp(-math.pi / 2)) < 1e-12, f"j^j on the principal branch is e^(-pi/2) = 0.2079; got {jj0}."
assert abs(jj1 - math.exp(-math.pi / 2 - 2 * math.pi)) < 1e-15, f"On the branch k = 1 it is e^(-5pi/2) = 0.000388; got {jj1}."
```

::: right
Right. $j^j$ is real on every branch: 0.2079 on the principal one and $3.88 \times 10^{-4}$ on the next.
:::
:::

::: check
kind: python

## Write `nth_roots(w, n)` returning the n roots of w. Set `poles` to the left-half-plane roots of $s^8 = -1$, the poles of a fourth-order Butterworth filter, sorted by imaginary part.

```python starter
import cmath, math

def nth_roots(w, n):
    return [w]

poles = sorted([p for p in nth_roots(-1, 8) if p.real < 0], key=lambda p: p.imag)
print(poles)
```

```python solution
import cmath, math

def nth_roots(w, n):
    r, t = abs(w), cmath.phase(w)
    return [r**(1 / n) * cmath.exp(1j * (t + 2 * math.pi * k) / n) for k in range(n)]

poles = sorted([p for p in nth_roots(-1, 8) if p.real < 0], key=lambda p: p.imag)
print(poles)
```

```python tests
assert len(nth_roots(8j, 3)) == 3 and all(abs(r**3 - 8j) < 1e-12 for r in nth_roots(8j, 3)), "Each of the three cube roots of 8j should cube back to 8j."
assert len(poles) == 4, f"A fourth-order filter has four poles; got {len(poles)}."
assert sorted(round(p.real, 5) for p in poles) == [-0.92388, -0.92388, -0.38268, -0.38268], f"The real parts should be -cos 22.5 and -cos 67.5 degrees; got {[p.real for p in poles]}."
```

::: right
Right. $-0.3827 \pm 0.9239j$ and $-0.9239 \pm 0.3827j$, evenly spaced on the left half of the unit circle.
:::
:::

::: check
kind: python

## Map the constant-resistance line $z = 2 + jx$, $-50 \le x \le 50$ (2001 points), through $\Gamma = \frac{z - 1}{z + 1}$. Set `dev` to the largest distance of the image from the circle with center $\frac{r}{r + 1}$ and radius $\frac{1}{r + 1}$, and `back` to the largest error after mapping back with $z = \frac{1 + \Gamma}{1 - \Gamma}$.

```python starter
import numpy as np

r = 2.0
x = np.linspace(-50, 50, 2001)
dev = back = 1.0
print(dev, back)
```

```python solution
import numpy as np

gamma = lambda z: (z - 1) / (z + 1)
z_of = lambda g: (1 + g) / (1 - g)
r = 2.0
x = np.linspace(-50, 50, 2001)
g = gamma(r + 1j * x)
dev = np.max(np.abs(np.abs(g - r / (r + 1)) - 1 / (r + 1)))
back = np.max(np.abs(z_of(g) - (r + 1j * x)))
print(dev, back)
```

```python tests
assert dev < 1e-12, f"Every point should lie on the circle to rounding error; got {dev}."
assert back < 1e-9, f"Mapping back should recover the line; got {back}."
```

::: right
Right. The image sits on the circle to about $10^{-16}$, and the inverse map recovers the line.
:::
:::

::: check
kind: python

## Write `image_area(f, z0, h)`: map the corners of the square with corners $z_0$, $z_0 + h$, $z_0 + h + jh$, $z_0 + jh$ through f and return the area of the resulting quadrilateral (the shoelace formula). Set `ratio` to that area over $h^2$ for $f = z^2$, $z_0 = 1 + j$ and $h = 10^{-4}$.

```python starter
def image_area(f, z0, h):
    return h * h

ratio = image_area(lambda z: z**2, 1 + 1j, 1e-4) / 1e-8
print(ratio)
```

```python solution
def image_area(f, z0, h):
    w = [f(c) for c in [z0, z0 + h, z0 + h + 1j * h, z0 + 1j * h]]
    s = sum(w[i].real * w[(i + 1) % 4].imag - w[(i + 1) % 4].real * w[i].imag for i in range(4))
    return abs(s) / 2

ratio = image_area(lambda z: z**2, 1 + 1j, 1e-4) / 1e-8
print(ratio)
```

```python tests
assert abs(ratio - 8) < 0.01, f"The area should grow by |f'|^2 = |2(1 + j)|^2 = 8; got {ratio}."
assert abs(image_area(lambda z: 3j * z, 0, 1) - 9) < 1e-12, "Multiplying by 3j scales areas by 9."
```

::: right
Right. 8.0008: the area grows by $\lvert f'\rvert^2 = 8$, plus a correction that shrinks with h.
:::
:::

::: explain
## Why is the best step for a numerical derivative neither very large nor very small?

::: model
A difference quotient has two kinds of error. Truncation error comes from the curvature the formula ignores and shrinks as the step gets smaller, as $h^2$ for a central difference. Rounding error comes from subtracting two nearly equal function values, each stored to about 16 digits; that absolute error, about $10^{-16}$ times the function's size, is then divided by h, so it grows as the step shrinks. The total is smallest where the two are about equal, which for a central difference is near $h \approx (10^{-16})^{1/3}$, about $10^{-5}$ for a function of ordinary size, with an error around $10^{-10}$.
:::
:::

::: practice

::: check
given: h = 0.1 | 0.05 | 0.02 | 0.01 | 0.005 | 0.002
answer: h^2
tolerance: 0.5%

## Central-difference error for $z^3$ with h = {h}?

::: misses
- [any] Exactly $h^2$.
:::
:::

::: check
given: a = 0.5 | 3; b = 2 | 1
answer: 4*(a^2 + b^2)
tolerance: 0.5%

## Area factor of $z^2$ at $\given{a} + \given{b}j$?

::: misses
- [any] $\lvert 2z_0\rvert^2$.
:::
:::
:::
