---
title: "Lab: complex numbers in Python"
heading: Python already speaks complex numbers
eyebrow: A3 · Lesson 10 · Lab: complex numbers in Python
xp: 60
---

::: hook
Python has complex numbers built in. Type `3+4j` and you get the point $(3, 4)$, with the engineer's $j$ and everything. The `cmath` module adds the complex versions of `sqrt`, `exp` and the conversions to polar form. In this lab you'll use them to solve any quadratic, find all the roots of a complex number, and watch a ringing circuit's natural response decay exactly as its roots say it should. If you haven't started A4 yet, its lessons on functions, loops and lists (lessons 1 to 8) cover the Python used here.
:::

::: play
- The curve is $\text{Re}\,e^{st}$ for a root $s = -\sigma + j\omega$: a ringing response.
- Move $\sigma$ and $\omega$. The dashed envelope is $e^{-\sigma t}$, and the curve rings at $\omega$ inside it.
- The readout gives the ratio of one peak to the next. It depends on $\sigma$ and $\omega$ together, through $2\pi\sigma/\omega$.
:::

```sim plot
view: graph
x: t = 0..50m s
y: v = -1.1..1.1
slider: sig = 0..200 = 50
slider: w = 200..2000 = 628
plot: exp(-sig*t)*cos(w*t) | samples: 800 | label: Re e^(st)
plot: exp(-sig*t) | dashed | color: ch2 | label: envelope
plot: -exp(-sig*t) | dashed | color: ch2
readout: peak-to-peak ratio = exp(-2*pi*sig/w) | digits: 4
```

::: predict
## What does Python print for `(1j)**2`?

- [x] `(-1+0j)`
- [ ] `-1`
- [ ] `1j`
- [ ] An error: you can't square $j$

::: reveal
It prints `(-1+0j)`. Python keeps the result complex even when its imaginary part is zero, so it shows both parts. `1j` is how Python writes $j$ alone; a bare `j` would be read as a variable name.
:::
:::

::: nameit
## Complex numbers in Python

- **Making one:** `z = 3 + 4j`, or `complex(3, 4)`. The `j` must follow a number directly, so write `1j`, never `j`.
- **Parts:** `z.real` is 3.0, `z.imag` is 4.0, and `z.conjugate()` is `(3-4j)`.
- **Length:** `abs(z)` gives 5.0.
- **Arithmetic:** `+`, `-`, `*`, `/` and `**` all work as in the lessons.

## The cmath module

`import cmath` adds:
- `cmath.phase(z)`: the angle in radians, from $-\pi$ to $\pi$ (it uses atan2, so the quadrant is right);
- `cmath.polar(z)`: the pair `(r, angle)`;
- `cmath.rect(r, angle)`: back from polar, with the angle in radians;
- `cmath.exp(z)`, `cmath.sqrt(z)` and `cmath.log(z)`: these accept complex numbers, where the `math` versions raise an error.

`math.degrees` and `math.radians` convert angles.

## The pieces this lab builds

- **Roots of $as^2 + bs + c$:** with `cmath.sqrt`, the quadratic formula works whatever the sign of $b^2 - 4ac$.
- **The $n$ roots of $z$:** $r^{1/n}e^{j(\theta + 2\pi k)/n}$ for $k = 0, 1, \ldots, n - 1$.
- **A natural response:** $\text{Re}\,e^{st}$ sampled at many times. Its successive peaks shrink by exactly $e^{-2\pi\sigma/\omega}$, because they're one period, $2\pi/\omega$, apart.
:::

::: example
## What does Python give for `cmath.polar(-4+3j)`, and what is the angle in degrees?

::: solution
1. **Python's answer.** It gives `(5.0, 2.498...)`: the length is
   $$\sqrt{16 + 9} = 5$$
   and the angle is 2.498 rad.
2. **Convert to degrees.** `math.degrees(2.498)` is 143.13°, in the second quadrant where $(-4, 3)$ sits.
3. **The wrong way.** A plain `math.atan(3 / -4)` would give $-36.87°$, in the wrong quadrant.

**Answer:** `(5.0, 2.498...)`, a length of 5 and an angle of 2.498 rad, which is 143.13°.
:::
:::

::: example
## Find the cube roots of $8j$ the way the lab's function will.

::: solution
1. **Polar form.** $8j$ has length 8 and angle 90°.
2. **Length of the roots.**
   $$8^{1/3} = 2$$
3. **Angles of the roots.** For $k = 0, 1, 2$:
   $$\frac{90° + 360°k}{3} = 30°,\ 150°,\ 270°$$
4. **Rectangular form.** They're $1.732 + j$, $-1.732 + j$ and $-2j$.
5. **Check in Python.** Cubing any of them, as in `(-2j)**3`, gives back `8j` (to rounding).

**Answer:** the cube roots are $1.732 + j$, $-1.732 + j$ and $-2j$.
:::
:::

::: example
## A response has $s = -50 + j628$ per second. By what factor does each peak shrink?

::: solution
1. **Time between peaks.** The peaks are one period apart:
   $$\begin{aligned} T &= \frac{2\pi}{628}\ \text{s} \\ &= 10\ \text{ms} \end{aligned}$$
2. **Envelope over one period.** Over that time the envelope $e^{-50t}$ falls by
   $$\begin{aligned} e^{-50 \times 0.01} &= e^{-0.5} \\ &= 0.607 \end{aligned}$$

**Answer:** each peak is 60.7% of the one before.
:::
:::

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

## What does `cmath.phase` return for the complex number $\given{a} + (\given{b})j$?

::: right
Right. {answer} radians, the angle of $(\given{a}, \given{b})$ in its own quadrant.
:::

::: misses
- [arg(a + j*b)*180/pi] That's in degrees. `cmath.phase` returns radians.
- [atan(b/a)] That's `math.atan(b / a)`, which can land in the wrong quadrant.
- [any] Not yet. Find the angle of the point, in radians, between $-\pi$ and $\pi$.
:::
:::

::: check
given: s = 20 | 50 | 100; w = 300 | 628 | 1500
answer: exp(-2*pi*s/w)
tolerance: 0.5%

## A natural response is $\text{Re}\,e^{st}$ with $s = -\given{s} + j\given{w}$. What is the ratio of each peak to the one before?

::: right
Right. The peaks are $2\pi/\omega$ apart, so the ratio is $e^{-2\pi\sigma/\omega}$ = {answer}.
:::

::: misses
- [exp(-s/w)] The peaks are a whole period apart: $2\pi/\omega$.
- [exp(-pi*s/w)] That's half a period, from a peak to the next trough.
- [any] Not yet. The envelope $e^{-\sigma t}$ over one period.
:::
:::

::: check
kind: python

## Write `polar_deg(z)`, returning `(r, degrees)`, and `from_polar_deg(r, deg)`, returning the complex number. Use `abs`, `cmath.phase`, `cmath.rect` and `math.radians`/`math.degrees`.

```python starter
import cmath, math

def polar_deg(z):
    return 0, 0

def from_polar_deg(r, deg):
    return 0j

print(polar_deg(-4 + 3j), from_polar_deg(10, -30))
```

```python solution
import cmath, math

def polar_deg(z):
    return abs(z), math.degrees(cmath.phase(z))

def from_polar_deg(r, deg):
    return cmath.rect(r, math.radians(deg))

print(polar_deg(-4 + 3j), from_polar_deg(10, -30))
```

```python tests
import math
r, d = polar_deg(-4 + 3j)
assert abs(r - 5) < 1e-12 and abs(d - 143.13010235) < 1e-6, f"-4+3j is 5 at 143.13 degrees; got {r} at {d}."
r, d = polar_deg(-1 - 1j)
assert abs(d + 135) < 1e-9, f"-1-1j is at -135 degrees; got {d}."
z = from_polar_deg(10, -30)
assert abs(z - (8.660254037844387 - 5j)) < 1e-12, f"10 at -30 degrees is 8.660 - 5j; got {z}."
for z0 in (3 + 4j, -2 + 0.5j, -1 - 7j, 0.25 - 0.1j):
    assert abs(from_polar_deg(*polar_deg(z0)) - z0) < 1e-12, "Converting to polar and back should return the same number."
```

::: right
Right. These two functions are all the polar arithmetic you'll need; everything else Python does in rectangular form.
:::
:::

::: check
kind: python

## Write `quadratic_roots(a, b, c)`, returning the two roots of $as^2 + bs + c = 0$ as a pair, the one with the `+` sign first. Use `cmath.sqrt` so it works for any discriminant.

```python starter
import cmath, math

def quadratic_roots(a, b, c):
    d = math.sqrt(b * b - 4 * a * c)
    return (-b + d) / (2 * a), (-b - d) / (2 * a)

print(quadratic_roots(1, 2, 5))
```

```python solution
import cmath, math

def quadratic_roots(a, b, c):
    d = cmath.sqrt(b * b - 4 * a * c)
    return (-b + d) / (2 * a), (-b - d) / (2 * a)

print(quadratic_roots(1, 2, 5))
```

```python tests
r1, r2 = quadratic_roots(1, 2, 5)
assert abs(r1 - (-1 + 2j)) < 1e-12 and abs(r2 - (-1 - 2j)) < 1e-12, f"s^2 + 2s + 5 has roots -1 ± 2j; got {r1}, {r2}."
r1, r2 = quadratic_roots(1, 400, 1e6)
assert abs(r1 - complex(-200, 979.7958971)) < 1e-6, f"The RLC circuit's roots are -200 ± 979.8j; got {r1}."
r1, r2 = quadratic_roots(2, -3, -2)
assert abs(r1 - 2) < 1e-12 and abs(r2 + 0.5) < 1e-12, "Real roots should still come out right: 2 and -0.5."
r1, r2 = quadratic_roots(1, -4, 4)
assert abs(r1 - 2) < 1e-12 and abs(r2 - 2) < 1e-12, "A repeated root, 2, should come out twice."
```

::: right
Right. The `math` version raised an error at the first negative discriminant; `cmath` just carries on into the complex plane.
:::
:::

::: check
kind: python

## Write `nth_roots(z, n)`, returning a list of all `n` roots of `z`, in order of $k = 0, 1, \ldots, n - 1$: length $|z|^{1/n}$ and angle $(\theta + 2\pi k)/n$, with $\theta$ = `cmath.phase(z)`.

```python starter
import cmath, math

def nth_roots(z, n):
    return [z ** (1 / n)]

print(nth_roots(8j, 3))
```

```python solution
import cmath, math

def nth_roots(z, n):
    r, th = abs(z) ** (1 / n), cmath.phase(z)
    return [cmath.rect(r, (th + 2 * math.pi * k) / n) for k in range(n)]

print(nth_roots(8j, 3))
```

```python tests
import cmath, math
roots = nth_roots(8j, 3)
assert len(roots) == 3, "There should be three cube roots."
want = [math.sqrt(3) + 1j, -math.sqrt(3) + 1j, -2j]
assert all(abs(a - b) < 1e-12 for a, b in zip(roots, want)), f"The cube roots of 8j are 1.732+j, -1.732+j and -2j; got {roots}."
for z, n in [(1, 5), (-16, 4), (3 - 4j, 6)]:
    rs = nth_roots(z, n)
    assert len(rs) == n and all(abs(w ** n - z) < 1e-9 for w in rs), f"Each of the {n} roots of {z}, raised to the power {n}, should give {z} back."
assert abs(sum(nth_roots(1, 7))) < 1e-12, "The seven 7th roots of 1 are spread evenly round the circle, so they sum to zero."
```

::: right
Right. The roots sit evenly around a circle, $360°/n$ apart, which is why they always sum to zero for $n \ge 2$.
:::
:::

::: check
kind: python

## Write `peak_ratio(s, T, steps)`. It samples $v(t) = \text{Re}\,e^{st}$ at `steps` evenly spaced times from 0 to `T`, finds the local maxima (samples bigger than both neighbors), and returns the average ratio of each peak to the one before. The test checks it against $e^{-2\pi\sigma/\omega}$.

```python starter
import cmath, math

def peak_ratio(s, T, steps):
    return 1

print(peak_ratio(complex(-50, 628), 0.05, 50000))
```

```python solution
import cmath, math

def peak_ratio(s, T, steps):
    v = [cmath.exp(s * T * k / (steps - 1)).real for k in range(steps)]
    peaks = [v[k] for k in range(1, steps - 1) if v[k] > v[k - 1] and v[k] > v[k + 1]]
    ratios = [peaks[i + 1] / peaks[i] for i in range(len(peaks) - 1)]
    return sum(ratios) / len(ratios)

print(peak_ratio(complex(-50, 628), 0.05, 50000))
```

```python tests
import math
r = peak_ratio(complex(-50, 628), 0.05, 50000)
assert abs(r - math.exp(-2 * math.pi * 50 / 628)) < 1e-3, f"For s = -50 + 628j the peaks shrink by e^(-0.5) = 0.607; got {r}."
r = peak_ratio(complex(-200, 2000), 0.02, 50000)
assert abs(r - math.exp(-2 * math.pi * 200 / 2000)) < 1e-3, f"For s = -200 + 2000j the ratio should be e^(-0.628) = 0.534; got {r}."
r = peak_ratio(complex(0, 1000), 0.05, 50000)
assert abs(r - 1) < 1e-3, "With no decay, every peak is the same height."
```

::: right
Right. The roots predict the decay without simulating anything; the samples confirm it.
:::
:::

::: explain
## Why does `math.sqrt(-4)` raise an error while `cmath.sqrt(-4)` returns `2j`? When is each the right tool?

::: model
The two modules answer different questions. `math` works only with real numbers, and no real number squares to −4, so it reports an error: in a calculation that's supposed to stay real, a negative under a root usually means a mistake, and failing loudly is helpful. `cmath` works in the complex plane, where every number has square roots, so it returns $2j$ (and $-2j$ is the other root). In EE the complex answer is often the meaningful one: a circuit whose characteristic equation has a negative discriminant really does ring, at a frequency set by the imaginary part. Use `math` when a negative value would be a bug, and `cmath` when complex results are expected, such as roots of characteristic equations, impedances and phasors.
:::
:::

::: practice

::: check
given: a = -5..5; b = -5..5
answer: arg(a + j*b)
tolerance: 0.5%

## `cmath.phase` of $\given{a} + (\given{b})j$?

::: misses
- [any] The angle in radians, from $-\pi$ to $\pi$.
:::
:::

::: check
given: s = 5..200; w = 100..5000
answer: exp(-2*pi*s/w)
tolerance: 0.5%

## Peak-to-peak ratio for $s = -\given{s} + j\given{w}$?

::: misses
- [any] $e^{-2\pi\sigma/\omega}$.
:::
:::
:::
