---
title: "Lab: phasor circuits in Python"
heading: A few functions that solve any AC divider
eyebrow: A3 · Lesson 17 · Lab: phasor circuits in Python
xp: 60
---

::: hook
With impedances, every AC circuit becomes Ohm's law with complex numbers, and Python's complex numbers do the arithmetic for you. In this lab you'll write a small toolkit: impedances of R, L and C, series and parallel combinations, a divider, a frequency sweep, and a solver that finds a filter's corner on its own. By the end, a filter you can write as $Z$'s is one you can analyze at any frequency in a line or two. If you haven't started A4 yet, its lessons on functions, loops and lists (lessons 1 to 9) cover the Python used here.
:::

::: play
- The curve is $|I|$ for a series RLC circuit driven by 10 V amplitude, plotted against frequency on a log axis.
- Move $R$, $L$ and $C$. The peak sits at $f_0 = 1/(2\pi\sqrt{LC})$, where the inductor and capacitor cancel and only $R$ limits the current.
- Lower $R$ and watch the peak grow taller and narrower.
:::

```sim plot
view: graph
x: f = 100..100k Hz log
y: I = 0..0.25 A
slider: R = 40..500 = 100 Ω
slider: L = 1..20 = 10 mH
slider: C = 0.5..10 = 2.2 µF
plot: 10/sqrt(R^2 + (2*pi*f*L*1e-3 - 1/(2*pi*f*C*1e-6))^2) | samples: 600 | label: |I|
marker: f = 1/(2*pi*sqrt(L*1e-3*C*1e-6)) | label: f0
readout: f0, Hz = 1/(2*pi*sqrt(L*1e-3*C*1e-6)) | digits: 4
readout: peak current, A = 10/R | digits: 3
```

::: predict
## At the resonant frequency of a series RLC circuit, how big is the voltage across the capacitor compared with the source?

- [ ] Always smaller, since it's only part of the circuit
- [ ] Exactly equal
- [x] It can be many times bigger
- [ ] Zero, since the reactances cancel

::: reveal
It can be many times bigger. At resonance the current is $V/R$, and the capacitor's voltage is that current times its reactance, $\frac{V}{R}\cdot\frac{1}{\omega_0C} = QV$. With a small $R$, $Q$ can be 10 or 100. The inductor's voltage is just as big and points the opposite way, so the two cancel in the sum and only the resistor's voltage, equal to the source, remains. Components in a resonant circuit must be rated for that higher voltage.
:::
:::

::: nameit
## Impedances as functions

Each part becomes a one-line function of frequency:

```python
import math

def zR(R, f): return complex(R, 0)
def zL(L, f): return 1j * 2 * math.pi * f * L
def zC(C, f): return 1 / (1j * 2 * math.pi * f * C)
```

Series impedances add, and parallel ones add as reciprocals:

$$Z_\text{series} = Z_1 + Z_2 + \cdots \qquad Z_\text{parallel} = \frac{1}{1/Z_1 + 1/Z_2 + \cdots}$$

A function can take any number of arguments with `*zs`, which collects them into a list.

## Dividers and transfer functions

The output across $Z_2$ of a divider $Z_1$ over $Z_2$ is $H = \frac{Z_2}{Z_1 + Z_2}$. Its size $|H|$ is the gain, $20\log_{10}|H|$ the gain in decibels, and its angle the phase shift. Writing $H$ as a Python function of $f$ lets you evaluate it anywhere.

## Finding a corner

A low-pass corner is where $|H|$ has fallen to $1/\sqrt{2}$ of its low-frequency value, $-3.01$ dB. For a simple RC it's $1/(2\pi RC)$, but for most filters there's no formula. Bisection finds it: $|H| - 1/\sqrt{2}$ changes sign across the corner, so halve a bracket of frequencies until it's tight. On a log axis, bisect in the logarithm of $f$, taking the midpoint $\sqrt{f_\text{lo}f_\text{hi}}$, so a bracket spanning decades closes evenly.
:::

::: example
## Evaluate an RC low-pass with $R$ = 1 kΩ and $C$ = 100 nF at its corner, as the lab's code will.

::: solution
1. **Corner frequency.**
   $$\begin{aligned} f_c &= \frac{1}{2\pi \times 1000 \times 10^{-7}}\ \text{Hz} \\ &= 1591.5\ \text{Hz} \end{aligned}$$
2. **The response there.**
   $$\begin{aligned} H &= \frac{1}{1 + j\omega RC} \\ &= \frac{1}{1 + j} \end{aligned}$$
3. **What Python gives.** Python gives `(0.5-0.5j)`: size $0.7071$, or $-3.01$ dB, at an angle of $-45°$.

**Answer:** at the 1591.5 Hz corner, $H$ is `(0.5-0.5j)`, a size of 0.7071 ($-3.01$ dB) at $-45°$.
:::
:::

::: example
## A series circuit of 100 Ω, 10 mH and 2.2 µF is driven by 10 V amplitude at 1 kHz. What current flows?

::: solution
1. **Impedance.**
   $$\begin{aligned} Z &= 100 + j62.83 \\ &\quad + \frac{1}{j \times 0.01382} \\ &= 100 + j62.83 - j72.34 \\ &= 100 - j9.51\ \Omega \end{aligned}$$
2. **Current.**
   $$\begin{aligned} I &= \frac{10}{Z} \\ &= 0.0996\angle 5.4°\ \text{A} \end{aligned}$$
3. **Compare with resonance.** That's almost 0.1 A, since 1 kHz is close to the resonance at 1.07 kHz, where the current would be $10/100$ = 0.1 A exactly.

**Answer:** a current of $0.0996\angle 5.4°$ A flows, almost 0.1 A.
:::
:::

::: example
## How many bisection steps in $\log f$ narrow a corner bracket from [10 Hz, 1 MHz] to within 0.1%?

::: solution
1. **Span of the bracket.**
   $$\log_{10}(10^6/10) = 5\ \text{decades}$$
2. **Target width.** Within 0.1% means a ratio of 1.001, which in decades is
   $$\log_{10} 1.001 = 0.000\,434$$
3. **Count the halvings.** Each step halves the span in decades, so it takes
   $$\begin{aligned} &\lceil\log_2(5/0.000\,434)\rceil \\ &= \lceil 13.49\rceil \\ &= 14\ \text{steps} \end{aligned}$$

**Answer:** 14 steps.
:::
:::

::: check
given: R = 1 | 4.7 | 10; C = 10 | 47 | 100
answer: 1/(2*pi*R*1e3*C*1e-9)
unit: Hz
tolerance: 0.5%

## Where should a corner-finding routine land for an RC low-pass with {R} kΩ and {C} nF?

::: right
Right. $1/(2\pi RC)$ = {answer}, where $|H|$ is $1/\sqrt{2}$.
:::

::: misses
- [1/(R*1e3*C*1e-9)] That's $\omega$ in rad/s.
- [any] Not yet. The corner is where $\omega RC = 1$.
:::
:::

::: check
given: V = 5 | 10; R = 20 | 50; L = 10 | 50; C = 1 | 10
answer: V/R*sqrt(L*1e-3/(C*1e-6))
unit: V
tolerance: 0.5%

## A series RLC circuit ({R} Ω, {L} mH, {C} µF) is driven at resonance with {V} V amplitude. What is the amplitude across the capacitor?

::: right
Right. $I = V/R$ and $|V_C| = I/\omega_0C = \frac{V}{R}\sqrt{L/C}$ = {answer}.
:::

::: misses
- [V] The capacitor and inductor voltages cancel each other in the sum, but each alone can be far bigger than the source.
- [any] Not yet. Find the current at resonance, then multiply by $1/\omega_0C$.
:::
:::

::: check
kind: python

## Write `zR(R, f)`, `zL(L, f)` and `zC(C, f)`, returning complex impedances, and `series(*zs)` and `parallel(*zs)`, which combine any number of them.

```python starter
import math

def zR(R, f): return 0j
def zL(L, f): return 0j
def zC(C, f): return 0j
def series(*zs): return 0j
def parallel(*zs): return 0j

print(series(zR(100, 1000), zL(0.01, 1000), zC(2.2e-6, 1000)))
```

```python solution
import math

def zR(R, f): return complex(R, 0)
def zL(L, f): return 1j * 2 * math.pi * f * L
def zC(C, f): return 1 / (1j * 2 * math.pi * f * C)
def series(*zs): return sum(zs)
def parallel(*zs): return 1 / sum(1 / z for z in zs)

print(series(zR(100, 1000), zL(0.01, 1000), zC(2.2e-6, 1000)))
```

```python tests
import math
z = series(zR(100, 1000), zL(0.01, 1000), zC(2.2e-6, 1000))
assert abs(z - complex(100, -9.511302879)) < 1e-6, f"100 ohms, 10 mH and 2.2 uF in series at 1 kHz is 100 - 9.51j; got {z}."
assert abs(zL(0.01, 1000) - 62.83185307j) < 1e-6 and abs(zC(1e-6, 1000) + 159.1549431j) < 1e-6, "Check zL = j2pifL and zC = 1/(j2pifC)."
p = parallel(zR(1000, 1000), zC(100e-9, 1000))
assert abs(p - 1000 / (1 + 0.6283185307j)) < 1e-6, f"1 kohm in parallel with 100 nF at 1 kHz is 717 - 450j; got {p}."
assert abs(parallel(zR(100, 1), zR(100, 1), zR(100, 1)) - 100 / 3) < 1e-12, "Three 100 ohm resistors in parallel make 33.3 ohms."
```

::: right
Right. With these five functions, any ladder of R, L and C reduces to one complex number per frequency.
:::
:::

::: check
kind: python

## Write `divider(z1, z2)`, returning $H = Z_2/(Z_1 + Z_2)$, and `rc_lowpass(R, C, f)`, built from your impedance functions, returning the low-pass's $H$ at `f`. Then `db(H)` returns $20\log_{10}|H|$ and `deg(H)` its angle in degrees.

```python starter
import cmath, math

def zR(R, f): return complex(R, 0)
def zC(C, f): return 1 / (1j * 2 * math.pi * f * C)

def divider(z1, z2): return 0j
def rc_lowpass(R, C, f): return 0j
def db(H): return 0
def deg(H): return 0

H = rc_lowpass(1000, 100e-9, 1591.55)
print(H, db(H), deg(H))
```

```python solution
import cmath, math

def zR(R, f): return complex(R, 0)
def zC(C, f): return 1 / (1j * 2 * math.pi * f * C)

def divider(z1, z2): return z2 / (z1 + z2)
def rc_lowpass(R, C, f): return divider(zR(R, f), zC(C, f))
def db(H): return 20 * math.log10(abs(H))
def deg(H): return math.degrees(cmath.phase(H))

H = rc_lowpass(1000, 100e-9, 1591.55)
print(H, db(H), deg(H))
```

```python tests
import math
fc = 1 / (2 * math.pi * 1000 * 100e-9)
H = rc_lowpass(1000, 100e-9, fc)
assert abs(H - (0.5 - 0.5j)) < 1e-12, f"At the corner, H = 1/(1 + j) = 0.5 - 0.5j; got {H}."
assert abs(db(H) + 3.0103) < 1e-4 and abs(deg(H) + 45) < 1e-9, f"At the corner: -3.01 dB at -45 degrees; got {db(H)} dB, {deg(H)} degrees."
H = rc_lowpass(1000, 100e-9, 100 * fc)
assert abs(db(H) + 40.0004) < 1e-3, f"Two decades above the corner it's about -40 dB; got {db(H)}."
assert abs(divider(1, 1) - 0.5) < 1e-12 and abs(divider(1j, -1j + 2) - (2 - 1j) / 2) < 1e-12, "divider(z1, z2) should be z2 / (z1 + z2)."
```

::: right
Right. Swap `zC` for `zL`, or the two arguments around, and the same function gives you every first-order filter.
:::
:::

::: check
kind: python

## Write `corner(H, f_lo, f_hi)`. `H` is a function of frequency for a low-pass whose $|H|$ starts near 1. Bisect in $\log f$ (midpoint $\sqrt{f_\text{lo}f_\text{hi}}$) for 60 steps to find where $|H| = 1/\sqrt{2}$, and return that frequency. The test uses it on an RC filter and on a two-stage filter that has no tidy formula.

```python starter
import math

def corner(H, f_lo, f_hi):
    return math.sqrt(f_lo * f_hi)

print(corner(lambda f: 1 / (1 + 1j * f / 1000), 10, 1e6))
```

```python solution
import math

def corner(H, f_lo, f_hi):
    target = 1 / math.sqrt(2)
    for _ in range(60):
        m = math.sqrt(f_lo * f_hi)
        if abs(H(m)) > target:
            f_lo = m
        else:
            f_hi = m
    return math.sqrt(f_lo * f_hi)

print(corner(lambda f: 1 / (1 + 1j * f / 1000), 10, 1e6))
```

```python tests
import math
fc = corner(lambda f: 1 / (1 + 1j * f / 1000), 10, 1e6)
assert abs(fc - 1000) < 1e-6, f"A low-pass with its corner at 1 kHz should give 1000 Hz; got {fc}."
w = lambda f: 2 * math.pi * f
# Two RC stages, each 1 kohm and 100 nF, the second loading the first.
def H2(f):
    zc = 1 / (1j * w(f) * 100e-9)
    zb = zc * (1000 + zc) / (zc + 1000 + zc)
    return zb / (1000 + zb) * zc / (1000 + zc)
fc2 = corner(H2, 10, 1e6)
assert abs(abs(H2(fc2)) - 1 / math.sqrt(2)) < 1e-9, "At the corner found, |H| should be 1/sqrt(2)."
assert abs(fc2 - 595.62) < 0.05, f"The loaded two-stage filter's corner is at 595.6 Hz; got {fc2:.1f} Hz."
```

::: right
Right. Two loaded stages put the corner at 595.6 Hz, well below the 1592 Hz of one stage, and the solver found it without any formula.
:::
:::

::: check
kind: python

## Write `rlc_current(V, R, L, C, f)`, returning the complex current in a series RLC circuit driven by amplitude `V` at `f`, and `resonance(L, C)`, returning $f_0$. Use your impedance functions.

```python starter
import math

def zR(R, f): return complex(R, 0)
def zL(L, f): return 1j * 2 * math.pi * f * L
def zC(C, f): return 1 / (1j * 2 * math.pi * f * C)

def rlc_current(V, R, L, C, f): return 0j
def resonance(L, C): return 0

print(rlc_current(10, 100, 0.01, 2.2e-6, 1000), resonance(0.01, 2.2e-6))
```

```python solution
import math

def zR(R, f): return complex(R, 0)
def zL(L, f): return 1j * 2 * math.pi * f * L
def zC(C, f): return 1 / (1j * 2 * math.pi * f * C)

def rlc_current(V, R, L, C, f): return V / (zR(R, f) + zL(L, f) + zC(C, f))
def resonance(L, C): return 1 / (2 * math.pi * math.sqrt(L * C))

print(rlc_current(10, 100, 0.01, 2.2e-6, 1000), resonance(0.01, 2.2e-6))
```

```python tests
import math, cmath
I = rlc_current(10, 100, 0.01, 2.2e-6, 1000)
assert abs(abs(I) - 0.0995507) < 1e-6 and abs(math.degrees(cmath.phase(I)) - 5.4332) < 1e-3, f"At 1 kHz the current is 0.0996 A at +5.43 degrees; got {abs(I)} at {math.degrees(cmath.phase(I))}."
f0 = resonance(0.01, 2.2e-6)
assert abs(f0 - 1073.02) < 0.01, f"Resonance is at 1073.0 Hz; got {f0}."
I0 = rlc_current(10, 100, 0.01, 2.2e-6, f0)
assert abs(I0 - 0.1) < 1e-9, "At resonance the current is V/R, 0.1 A, in phase with the source."
Vc = abs(I0 * 1 / (1j * 2 * math.pi * f0 * 2.2e-6))
assert abs(Vc - 10 * math.sqrt(0.01 / 2.2e-6) / 100) < 1e-9, "The capacitor's voltage at resonance is (V/R) times sqrt(L/C)."
```

::: right
Right. At resonance the capacitor here holds 6.7 V while the source gives 10 V, and with a smaller resistor it would hold more than the source.
:::
:::

::: explain
## Why bisect in $\log f$ instead of $f$ when hunting for a filter's corner?

::: model
Filter behavior spreads evenly across decades, so a sensible starting bracket spans several of them, perhaps 10 Hz to 1 MHz. Bisecting in $f$ itself puts the first midpoint at about 500 kHz, and every early step spends its effort near the top of the range, so a corner at 500 Hz takes many steps just to get the bracket down to the right decade. Bisecting in $\log f$, with the midpoint $\sqrt{f_\text{lo}f_\text{hi}}$, halves the number of decades each time, so the bracket closes at the same relative rate wherever the corner is. The result is the same precision in a predictable number of steps, matching the log axis a Bode plot uses for the same reason.
:::
:::

::: practice

::: check
given: R = 0.1..100; C = 1..1000
answer: 1/(2*pi*R*1e3*C*1e-9)
unit: Hz
tolerance: 0.5%

## Corner of {R} kΩ and {C} nF, in Hz?

::: misses
- [any] $1/(2\pi RC)$.
:::
:::

::: check
given: L = 0.1..100; C = 0.01..10
answer: 1/(2*pi*sqrt(L*1e-3*C*1e-6))
unit: Hz
tolerance: 0.5%

## Resonance of {L} mH and {C} µF, in Hz?

::: misses
- [any] $1/(2\pi\sqrt{LC})$.
:::
:::
:::
