---
title: Complex numbers and units in code
heading: Phasors and impedances in a few lines of Python
eyebrow: A4 · Lesson 36 · Complex numbers in code
xp: 40
---

::: hook
In A3 you added phasors by converting to rectangular form, adding, and converting back, by hand. Python's complex numbers do all of that for you, and NumPy does it for a thousand frequencies at once. This is how filter responses get computed in practice.
:::

::: predict
## With `import numpy as np`, what does `np.angle(1j)` return?

- [ ] 90
- [x] 1.5707963...
- [ ] 1j
- [ ] 0.25

::: reveal
1.5707963..., which is $\pi/2$. NumPy and Python's `cmath` work in radians. `np.angle(z, deg=True)` gives degrees, and `np.degrees(x)` converts any radian value.
:::
:::

::: nameit
## Complex numbers are built in

Python writes $j$ after a number: `3 + 4j`, or `1j` on its own. `complex(a, b)` builds $a + jb$ from two variables. Arithmetic, including division, just works:

```
import numpy as np
z = 3 + 4j
abs(z)                    # 5.0
np.angle(z, deg=True)     # 53.13...
z.real, z.imag            # 3.0, 4.0
z.conjugate()             # (3-4j)
```

To build a number from polar form, use $re^{j\theta}$ directly: `r * np.exp(1j * theta)`, with θ in radians (`np.radians(deg)` converts).

**Impedances.** With $\omega = 2\pi f$:

```
w = 2 * np.pi * f
ZR = R
ZC = 1 / (1j * w * C)
ZL = 1j * w * L
```

Series impedances add; parallel ones combine as `Z1 * Z2 / (Z1 + Z2)`, the same formula as for resistors.

**Arrays of frequencies.** If `f` is an array, every line above computes all the frequencies at once, and `np.abs` and `np.angle` work element by element.

**Units.** Code has no units, so the course keeps every quantity in base SI units: ohms, farads, henries, hertz, seconds. A capacitor of 100 nF is `C = 100e-9`. If you keep to that, the formulas need no conversion factors.
:::

::: example
## Find the current in a 100 Ω resistor and 10 mH inductor in series, driven with 5 V amplitude at 1 kHz.

::: solution
1. **Build the impedance and divide.** $Z = R + j\omega L$, and the current is $5/Z$.

```
import cmath, math
Z = 100 + 1j * 2 * math.pi * 1000 * 10e-3
I = 5 / Z
print(abs(Z), math.degrees(cmath.phase(Z)))     # 118.1 32.14
print(abs(I) * 1e3, math.degrees(cmath.phase(I)))   # 42.34 -32.14
```

2. **Read the results.** $|Z|$ = 118.1 Ω at 32.14°, so
   $$\begin{aligned} |I| &= \frac{5\ \text{V}}{118.1\ \Omega} \\ &= 42.3\ \text{mA} \end{aligned}$$
   lagging the voltage by 32.1°.
3. **Compare.** It's the same answer A3's hand calculation gives, in three lines.

**Answer:** 42.3 mA, lagging the voltage by 32.1°.
:::
:::

::: example
## Add $3\angle 20°$ and $4\angle 110°$.

::: solution
1. **Make each phasor and add.** `cmath.exp(1j * θ)` turns each angle into a unit phasor.

```
S = 3 * cmath.exp(1j * math.radians(20)) + 4 * cmath.exp(1j * math.radians(110))
print(abs(S), math.degrees(cmath.phase(S)))     # 5.0 73.13
```

2. **Check.** They're 90° apart, so the length is
   $$\begin{aligned} |S| &= \sqrt{3^2 + 4^2} \\ &= 5 \end{aligned}$$
   as the code confirms.

**Answer:** the sum is $5\angle 73.13°$.
:::
:::

::: check
kind: python
given: C = 10n..10u E6 F; f = 50 | 1000 | 100000

## Write `zc(C, f)` that returns a capacitor's complex impedance, $1/(j2\pi fC)$.

`C` = {C} (in farads) and `f` = {f} Hz are already defined.

```python starter
import numpy as np

def zc(C, f):
    return 0

print(zc(C, f))
```

```python solution
import numpy as np

def zc(C, f):
    return 1 / (1j * 2 * np.pi * f * C)

print(zc(C, f))
```

```python tests
import numpy as np
z = zc(1e-6, 1000)
assert isinstance(z, complex) or np.iscomplexobj(z), "The impedance should be complex: use 1j in the formula."
assert abs(abs(z) - 1 / (2 * np.pi * 1000 * 1e-6)) < 1e-6, "For 1 µF at 1 kHz the size should be about 159.15 Ω."
assert abs(np.angle(z, deg=True) + 90) < 1e-6, "A capacitor's impedance points straight down: angle −90°. Check where the j goes."
assert abs(zc(C, f) - 1 / (1j * 2 * np.pi * f * C)) < 1e-9 * abs(zc(C, f)), "zc(C, f) doesn't match 1/(j·2π·f·C) for this lab's values."
```

::: right
Right. The `1j` in the bottom gives the −90°: dividing by $j$ turns the arrow a quarter turn back.
:::
:::

::: check
kind: python
given: R = 1k..10k E12 Ω; C = 10n..100n E6 F; f = 100 | 1000 | 10000

## An RC low-pass filter has $H = Z_C/(R + Z_C)$. Compute `mag`, the size of $H$ at {f} Hz, and `phase_deg`, its angle in degrees.

```python starter
import numpy as np

w = 2 * np.pi * f
ZC = 1 / (1j * w * C)
H = 0          # replace this
mag = 0        # replace this
phase_deg = 0  # replace this
print(mag, phase_deg)
```

```python solution
import numpy as np

w = 2 * np.pi * f
ZC = 1 / (1j * w * C)
H = ZC / (R + ZC)
mag = abs(H)
phase_deg = np.angle(H, deg=True)
print(mag, phase_deg)
```

```python tests
import numpy as np
want = 1 / (1 + 1j * 2 * np.pi * f * R * C)
assert abs(H - want) < 1e-9, "H should be ZC / (R + ZC)."
assert abs(mag - abs(want)) < 1e-9, "mag should be abs(H)."
assert abs(phase_deg - np.angle(want)) > 1e-6 or abs(np.angle(want)) < 1e-9, "That's in radians. Use np.angle(H, deg=True)."
assert abs(phase_deg - np.angle(want, deg=True)) < 1e-6, "phase_deg should be the angle of H in degrees."
```

::: right
Right. The phase is negative: the output lags the input, more so at higher frequencies.
:::
:::

::: check
kind: python
given: A1 = 1..5 int; p1 = -60..60 step 15; A2 = 1..5 int; p2 = 30..150 step 15

## Add the phasors $\given{A1}\angle\given{p1}°$ and $\given{A2}\angle\given{p2}°$ in code. Set `amp` to the sum's amplitude and `ang` to its angle in degrees.

```python starter
import numpy as np

V1 = 0   # replace: A1 at p1 degrees
V2 = 0   # replace: A2 at p2 degrees
S = V1 + V2
amp = 0
ang = 0
print(amp, ang)
```

```python solution
import numpy as np

V1 = A1 * np.exp(1j * np.radians(p1))
V2 = A2 * np.exp(1j * np.radians(p2))
S = V1 + V2
amp = abs(S)
ang = np.angle(S, deg=True)
print(amp, ang)
```

```python tests
import numpy as np
S2 = A1 * np.exp(1j * p1 * np.pi / 180) + A2 * np.exp(1j * p2 * np.pi / 180)
assert abs(V1 - A1 * np.exp(1j * np.radians(p1))) < 1e-9, "V1 should be A1·exp(j·radians(p1)): the angle in the exponent must be in radians."
assert abs(amp - abs(S2)) < 1e-9 and abs(ang - np.angle(S2, deg=True)) < 1e-6, "amp and ang should be the size and angle (in degrees) of V1 + V2."
```

::: right
Right. The four-step recipe from A3, done in three lines.
:::
:::

::: check
kind: choice

## Why does `1 / (1j * w * C)` give a capacitor's impedance in ohms, with no conversion factor?

- [x] Because `w` is in radians per second and `C` in farads, base SI units, so the result comes out in base units too
- [ ] Python converts the units automatically
- [ ] It's only right at one frequency
- [ ] Because `1j` carries the unit of ohms

::: right
Right. Keep every input in base SI units, and every result comes out in base SI units.
:::

::: misses
- [2] Python numbers have no units at all. The convention of using base units is what makes it work.
- [3] It's right at every frequency, as long as `w` is $2\pi f$ in radians per second.
- [4] `1j` is just the number $j$, with no units.
:::
:::

::: check
kind: python
given: R = 5 | 10 | 22; L = 1 | 2.2 | 4.7; C = 10 | 47 | 100

## A series RLC has `R` = {R} Ω, `L` = {L} mH and `C` = {C} nF. Using a NumPy array of 200,001 frequencies from 1 kHz to 100 kHz, compute the complex impedance $Z = R + j\omega L + 1/(j\omega C)$. Set `f_min` to the frequency where $|Z|$ is smallest and `Z_min` to that smallest $|Z|$. Then set `f0` to $1/(2\pi\sqrt{LC})$ for comparison.

```python starter
import numpy as np
f = np.linspace(1e3, 100e3, 200001)
w = 2 * np.pi * f
Z = R + w * L * 1e-3 + 1 / (w * C * 1e-9)
f_min = f[np.argmin(Z)]
Z_min = Z.min()
f0 = 0
print(f_min, Z_min, f0)
```

```python solution
import numpy as np
f = np.linspace(1e3, 100e3, 200001)
w = 2 * np.pi * f
Z = R + 1j * w * L * 1e-3 + 1 / (1j * w * C * 1e-9)
i = np.argmin(np.abs(Z))
f_min = f[i]
Z_min = np.abs(Z[i])
f0 = 1 / (2 * np.pi * np.sqrt(L * 1e-3 * C * 1e-9))
print(f_min, Z_min, f0)
```

```python tests
import numpy as np
F0 = 1 / (2 * np.pi * np.sqrt(L * 1e-3 * C * 1e-9))
assert abs(f0 - F0) < 1e-6 * F0, f"f0 should be {F0:.1f} Hz."
assert abs(f_min - F0) <= 0.5 * (99e3 / 200000) + 1e-9, f"The smallest |Z| should be at the grid point nearest {F0:.1f} Hz. Use 1j for the reactances and np.abs(Z)."
assert abs(Z_min - R) < 1e-3 * R, f"At resonance the reactances cancel and |Z| is R = {R} Ω."
```

::: right
Right. With `1j` the inductor's and capacitor's reactances have opposite signs and cancel at one frequency, leaving only $R$. Without the `j`, the reactances just add, and there's no resonance at all.
:::
:::

::: check
kind: choice

## What does `(1j) ** 2` give in Python?

- [x] `(-1+0j)`
- [ ] `-1`, an `int`
- [ ] `1j`
- [ ] An error

::: right
Right. $j^2 = -1$, and since `1j` is complex, so is the result: `(-1+0j)`. Python keeps it complex even though the imaginary part is zero.
:::

::: misses
- [2] The value is −1, but an operation on a complex number gives a complex number: `(-1+0j)`.
- [3] That's $j^1$. Squaring turns 90° into 180°: −1.
- [4] Powers of complex numbers are allowed in Python.
:::
:::

::: explain
## Why is it safer to keep every value in base SI units in code, rather than in the units printed on the parts?

::: model
Formulas like $1/(2\pi fC)$ assume base units. If C is stored as 100 (meaning nF) instead of 100e-9, every result is wrong by a factor of a billion, and nothing in the code warns you. Storing everything in base units means formulas work as written, and the conversion to friendly units happens only once, when the result is printed or plotted.
:::
:::

::: practice

::: check
kind: python
given: R = 10..1000 sig 2; L = 1m..100m E6 H; f = 50 | 1000 | 10000

## Set `Zmag` to the size of the impedance of {R} Ω in series with {L} at {f} Hz.

```python starter
import numpy as np

Zmag = 0
print(Zmag)
```

```python solution
import numpy as np

Z = R + 1j * 2 * np.pi * f * L
Zmag = abs(Z)
print(Zmag)
```

```python tests
import numpy as np
want = abs(R + 1j * 2 * np.pi * f * L)
assert abs(Zmag - (R + 2 * np.pi * f * L)) > 1e-6 * want, "The two parts are at right angles: add them as complex numbers, then take abs."
assert abs(Zmag - want) < 1e-9 * want, "Zmag should be abs(R + j·2π·f·L)."
```
:::

::: check
kind: python
given: R = 100..10k sig 2; C = 10n..1u E6 F; f = 100 | 1000

## Set `Zp` to the complex impedance of {R} Ω in parallel with {C} at {f} Hz.

```python starter
import numpy as np

Zp = 0
print(Zp)
```

```python solution
import numpy as np

ZC = 1 / (1j * 2 * np.pi * f * C)
Zp = R * ZC / (R + ZC)
print(Zp)
```

```python tests
import numpy as np
ZC = 1 / (1j * 2 * np.pi * f * C)
assert abs(Zp - R * ZC / (R + ZC)) < 1e-9 * abs(Zp), "Zp should be R·ZC / (R + ZC)."
```
:::

::: check
kind: python
given: Vm = 10..170 sig 2; pv = -30..30 step 10; Im = 1..9 int; pi1 = -50..0 step 10

## With amplitude phasors $\mathbf{V} = \given{Vm}\angle\given{pv}°$ and $\mathbf{I} = \given{Im}\angle\given{pi1}°$, set `P` to the average power, $\tfrac12\operatorname{Re}(\mathbf{V}\mathbf{I}^*)$.

```python starter
import numpy as np

V = Vm * np.exp(1j * np.radians(pv))
I = Im * np.exp(1j * np.radians(pi1))
P = 0
print(P)
```

```python solution
import numpy as np

V = Vm * np.exp(1j * np.radians(pv))
I = Im * np.exp(1j * np.radians(pi1))
P = 0.5 * np.real(V * np.conj(I))
print(P)
```

```python tests
import numpy as np
want = 0.5 * Vm * Im * np.cos(np.radians(pv - pi1))
assert abs(P - 0.5 * np.real(V * I)) > 1e-6 or abs(want - 0.5 * np.real(V * I)) < 1e-9, "Use the conjugate of I: np.conj(I)."
assert abs(P - want) < 1e-9 * max(1, abs(want)), "P should be ½·Re(V·conj(I))."
```
:::
:::
