---
title: AC solver lab
heading: A complex-number circuit solver and a frequency sweep in NumPy
eyebrow: C3 · Lesson 25 · AC solver lab
xp: 50
---

::: hook
A circuit simulator's AC analysis is the nodal solver of C1 with one change: the numbers are complex. Each capacitor and inductor contributes an admittance that depends on frequency, so the simulator builds and solves the matrix once per frequency, hundreds of times across a sweep, to draw a Bode plot. In this lab you'll extend C1's modified nodal analysis to complex admittances, check it against lesson 8's hand calculation, and sweep a filter and a resonant circuit.
:::

::: play
- An RC low-pass's gain against frequency, computed the way your solver will: one complex solve per frequency, here done by the course's own engine.
- At the corner, the gain is −3.01 dB; a decade above, about −20 dB.
- Change R or C and watch the whole curve slide: a sweep is many independent solves.
:::
:::

```sim circuit
V1 in 0 sine 1 V 1k Hz      @ 0,0 down
R1 in out 1k                @ 0,0 right
C1 out 0 100n               @ 2,0 down
slider: R1 100..10k log
slider: C1 10n..1u log
bode: v(out)/v(in) | f = 10..100k Hz
```

::: predict
## A solver sweeps a circuit at 200 frequencies. How many times does it build and solve the complex matrix?

- [ ] Once: the circuit is linear
- [ ] Twice: once for magnitude, once for phase
- [x] 200 times, once per frequency
- [ ] 400 times, real and imaginary parts separately

::: reveal
200 times. The admittances $j\omega C$ and $1/(j\omega L)$ change with frequency, so each frequency has its own matrix. Each solve gives magnitude and phase together, since the answer is complex. Real simulators reuse the matrix's pattern of nonzero entries between frequencies to save time.
:::
:::

::: nameit
## Complex admittances

Each part's admittance at angular frequency ω:

| Part | Impedance | Admittance |
|---|---|---|
| resistor | $R$ | $1/R$ |
| inductor | $j\omega L$ | $\frac{1}{j\omega L}$ |
| capacitor | $\frac{1}{j\omega C}$ | $j\omega C$ |

They stamp into the matrix exactly as conductances did in C1.25: $+y$ on the two diagonal entries, $-y$ on the two off-diagonal ones. Voltage sources add a row and column each (modified nodal analysis), with their phasor value on the right side.

## In NumPy

```python
A = np.zeros((n, n), dtype=complex)   # complex entries
y = 1 / (1j * w * L)                    # 1j is Python's j
v = np.linalg.solve(A, z)               # works with complex arrays
abs(v[0]), np.angle(v[0], deg=True)     # magnitude and phase
```

## Sweeping

A **Bode plot** solves at many frequencies, usually spaced evenly on a log scale (`np.logspace`), and plots $20\log_{10}|H|$ and the phase of $H = V_\text{out}/V_\text{in}$. With a 1 V source, $V_\text{out}$ is $H$ itself.
:::

::: example
## What admittances does the solver stamp for 1 mH and 1 µF at 1 kHz?

::: solution
1. **Inductor impedance.**
   $$\begin{aligned} Z_L &= j2\pi \times 1000 \times 10^{-3} \\ &= j6.28\ \Omega \end{aligned}$$
2. **Inductor admittance.**
   $$\begin{aligned} y_L &= \frac{1}{j6.28} \\ &= -j0.159\ \text{S} \end{aligned}$$
3. **Capacitor impedance.**
   $$\begin{aligned} Z_C &= \frac{1}{j2\pi \times 1000 \times 10^{-6}} \\ &= -j159\ \Omega \end{aligned}$$
4. **Capacitor admittance.**
   $$\begin{aligned} y_C &= \frac{1}{-j159} \\ &= j6.28\ \text{mS} \end{aligned}$$

**Answer:** it stamps $y_L = -j0.159$ S for the inductor and $y_C = j6.28$ mS for the capacitor.
:::
:::

::: example
## A series RLC (10 Ω, 10 mH, 100 nF) driven by 1 V: what gain does the solver find across the capacitor at resonance?

::: solution
1. **Current at resonance.** At $f_0 = 5.03$ kHz the current is
   $$\begin{aligned} I &= \frac{1\ \text{V}}{10\ \Omega} \\ &= 0.1\ \text{A} \end{aligned}$$
2. **The capacitor's reactance.**
   $$\begin{aligned} X_C &= \sqrt{L/C} \\ &= 316\ \Omega \end{aligned}$$
3. **Capacitor voltage.**
   $$\begin{aligned} |V_C| &= 0.1 \times 316 \\ &= 31.6\ \text{V} \end{aligned}$$
4. **Gain.** That's a gain of +30 dB, which is $Q = 31.6$.

**Answer:** a gain of 31.6, or +30 dB, which equals the circuit's Q.
:::
:::

::: check
given: L = 1 | 10 | 100; f = 0.1 | 1 | 10
answer: 2*pi*f*1000*L*1e-3
unit: Ω
tolerance: 0.5%

## What is the magnitude of the impedance the solver uses for {L} mH at {f} kHz?

::: right
Right. $\omega L$ = {answer}.
:::

::: misses
- [any] Not yet. $|Z_L| = 2\pi fL$.
:::
:::

::: check
given: C = 1 | 10 | 100; f = 0.1 | 1 | 10
answer: 2*pi*f*1000*C*1e-9*1000
unit: mS
tolerance: 0.5%

## What is the magnitude of the admittance for {C} nF at {f} kHz?

::: right
Right. $\omega C$ = {answer}.
:::

::: misses
- [1/(2*pi*f*1000*C*1e-9)*1000] That's the impedance; the admittance is $\omega C$.
- [any] Not yet. $|y_C| = 2\pi fC$.
:::
:::

::: check
given: n = 3 | 10 | 50; m = 1 | 2
answer: (n + m)^2
tolerance: 0.1%

## An AC MNA matrix has {n} node unknowns and {m} voltage sources. How many complex entries does it have?

::: right
Right. $(n + m)^2$ = {answer}.
:::

::: misses
- [n^2] Each voltage source adds a row and a column.
- [any] Not yet. Count unknowns, then square.
:::
:::

::: check
given: N = 20 | 100; d = 2 | 4 | 6
answer: N*d + 1
tolerance: 0.1%

## A sweep takes {N} points per decade over {d} decades, including both ends. How many solves does it need?

::: right
Right. $Nd + 1$ = {answer}.
:::

::: misses
- [N*d] Include the final endpoint.
- [any] Not yet. $N$ intervals per decade, plus the last point.
:::
:::

::: check
kind: python

## Write `impedance(kind, value, f)` returning a complex impedance for `'R'`, `'L'` or `'C'` at frequency `f` (Hz), and `ac_mna(netlist, n, f)` returning the complex node voltages for entries `('R'|'L'|'C', a, b, value)`, `('I', a, b, phasor)` and `('V', a, b, phasor)`.

```python starter
import numpy as np

def impedance(kind, value, f):
    return complex(value)

def ac_mna(netlist, n, f):
    return np.zeros(n, dtype=complex)

print(ac_mna([('V', 1, 0, 1.0), ('R', 1, 2, 1e3), ('C', 2, 0, 100e-9)], 2, 1591.55))
```

```python solution
import numpy as np

def impedance(kind, value, f):
    w = 2 * np.pi * f
    if kind == 'R':
        return complex(value)
    if kind == 'L':
        return 1j * w * value
    return 1 / (1j * w * value)

def ac_mna(netlist, n, f):
    vs = [e for e in netlist if e[0] == 'V']
    m = len(vs)
    A = np.zeros((n + m, n + m), dtype=complex)
    z = np.zeros(n + m, dtype=complex)
    for kind, a, b, val in netlist:
        if kind in ('R', 'L', 'C'):
            y = 1 / impedance(kind, val, f)
            for x, yy, s in ((a, a, 1), (b, b, 1), (a, b, -1), (b, a, -1)):
                if x and yy:
                    A[x - 1, yy - 1] += s * y
        elif kind == 'I':
            if a:
                z[a - 1] -= val
            if b:
                z[b - 1] += val
    for k, (_, a, b, val) in enumerate(vs):
        r = n + k
        if a:
            A[a - 1, r] += 1
            A[r, a - 1] += 1
        if b:
            A[b - 1, r] -= 1
            A[r, b - 1] -= 1
        z[r] = val
    return np.linalg.solve(A, z)[:n]

print(ac_mna([('V', 1, 0, 1.0), ('R', 1, 2, 1e3), ('C', 2, 0, 100e-9)], 2, 1591.55))
```

```python tests
import numpy as np
assert abs(impedance('L', 1e-3, 1000) - 6.283185307179586j) < 1e-9, "Z_L = jωL."
assert abs(impedance('C', 1e-6, 1000) + 159.15494309189535j) < 1e-6, "Z_C = 1/(jωC) = -j159 Ω at 1 kHz."
v = ac_mna([('V', 1, 0, 10.0), ('R', 1, 2, 1e3), ('C', 2, 0, 220e-9), ('R', 2, 3, 1e3), ('L', 3, 0, 0.1)], 3, 1000)
assert abs(abs(v[1]) - 5.11896786) < 1e-6 and abs(np.degrees(np.angle(v[1])) + 28.4894848) < 1e-5, f"Lesson 8's node a is 5.12 V at -28.5°; got {abs(v[1]):.4f} at {np.degrees(np.angle(v[1])):.2f}°."
assert abs(abs(v[2]) - 2.72338327) < 1e-6 and abs(np.degrees(np.angle(v[2])) - 29.3686076) < 1e-5, f"Node b is 2.72 V at +29.4°; got {abs(v[2]):.4f}."
fc = 1 / (2 * np.pi * 1e3 * 100e-9)
v = ac_mna([('V', 1, 0, 1.0), ('R', 1, 2, 1e3), ('C', 2, 0, 100e-9)], 2, fc)
assert abs(abs(v[1]) - 1 / np.sqrt(2)) < 1e-9, "At an RC's corner the output is 1/√2."
```

::: right
Right. That's lesson 8's two-node circuit, solved by machine instead of by Cramer's rule.
:::
:::

::: check
kind: python

## Write `gain_db(netlist, n, out, freqs)`: for a netlist driven by a 1 V source, return an array of $20\log_{10}|v_\text{out}|$ at each frequency in `freqs`. Your `ac_mna` is included.

```python starter
import numpy as np

def impedance(kind, value, f):
    w = 2 * np.pi * f
    return complex(value) if kind == 'R' else (1j * w * value if kind == 'L' else 1 / (1j * w * value))

def ac_mna(netlist, n, f):
    vs = [e for e in netlist if e[0] == 'V']
    m = len(vs)
    A = np.zeros((n + m, n + m), dtype=complex); z = np.zeros(n + m, dtype=complex)
    for kind, a, b, val in netlist:
        if kind in ('R', 'L', 'C'):
            y = 1 / impedance(kind, val, f)
            for x, yy, s in ((a, a, 1), (b, b, 1), (a, b, -1), (b, a, -1)):
                if x and yy: A[x - 1, yy - 1] += s * y
        elif kind == 'I':
            if a: z[a - 1] -= val
            if b: z[b - 1] += val
    for k, (_, a, b, val) in enumerate(vs):
        r = n + k
        if a: A[a - 1, r] += 1; A[r, a - 1] += 1
        if b: A[b - 1, r] -= 1; A[r, b - 1] -= 1
        z[r] = val
    return np.linalg.solve(A, z)[:n]

def gain_db(netlist, n, out, freqs):
    return np.zeros(len(freqs))
```

```python solution
import numpy as np

def impedance(kind, value, f):
    w = 2 * np.pi * f
    return complex(value) if kind == 'R' else (1j * w * value if kind == 'L' else 1 / (1j * w * value))

def ac_mna(netlist, n, f):
    vs = [e for e in netlist if e[0] == 'V']
    m = len(vs)
    A = np.zeros((n + m, n + m), dtype=complex); z = np.zeros(n + m, dtype=complex)
    for kind, a, b, val in netlist:
        if kind in ('R', 'L', 'C'):
            y = 1 / impedance(kind, val, f)
            for x, yy, s in ((a, a, 1), (b, b, 1), (a, b, -1), (b, a, -1)):
                if x and yy: A[x - 1, yy - 1] += s * y
        elif kind == 'I':
            if a: z[a - 1] -= val
            if b: z[b - 1] += val
    for k, (_, a, b, val) in enumerate(vs):
        r = n + k
        if a: A[a - 1, r] += 1; A[r, a - 1] += 1
        if b: A[b - 1, r] -= 1; A[r, b - 1] -= 1
        z[r] = val
    return np.linalg.solve(A, z)[:n]

def gain_db(netlist, n, out, freqs):
    return np.array([20 * np.log10(abs(ac_mna(netlist, n, f)[out - 1])) for f in freqs])
```

```python tests
import numpy as np
rc = [('V', 1, 0, 1.0), ('R', 1, 2, 1e3), ('C', 2, 0, 100e-9)]
fc = 1 / (2 * np.pi * 1e3 * 100e-9)
g = gain_db(rc, 2, 2, [fc / 10, fc, 10 * fc])
assert np.allclose(g, [-0.04321374, -3.01029996, -20.04321374], atol=1e-6), f"RC low-pass: about 0, -3.01 and -20.04 dB; got {g}."
rlc = [('V', 1, 0, 1.0), ('R', 1, 2, 10), ('L', 2, 3, 10e-3), ('C', 3, 0, 100e-9)]
f0 = 1 / (2 * np.pi * np.sqrt(10e-3 * 100e-9))
g = gain_db(rlc, 3, 3, [f0])
assert abs(g[0] - 30.0) < 1e-6, f"At resonance the capacitor voltage is Q = 31.6 times the input: +30 dB; got {g[0]:.4f}."
```

::: right
Right. Sweep `np.logspace(2, 5, 300)` and plot the result: you've drawn a Bode plot from a netlist, as SPICE's AC analysis does.
:::
:::

::: explain
## Why can a single complex solve give both the magnitude and the phase of a circuit's response?

::: model
A phasor packs a sinusoid's amplitude and phase into one complex number, and the circuit equations at one frequency are linear equations among phasors. Solving them with complex arithmetic produces each node voltage as a complex number, whose magnitude is the amplitude and whose angle is the phase relative to the source. Nothing is lost by solving once: the real and imaginary parts carry the in-phase and quadrature parts of the response, which together are exactly the magnitude and phase.
:::
:::

::: practice

::: check
given: f = 100 | 1000; L = 1 | 10
answer: 1/(2*pi*f*L*1e-3)
unit: S
tolerance: 0.5%

## What is the admittance magnitude of {L} mH at {f} Hz?

::: misses
- [any] $1/(\omega L)$.
:::
:::

::: check
given: g = -3 | -20 | -40
answer: 10^(g/20)
tolerance: 0.5%

## A gain of {g} dB is what voltage ratio?

::: misses
- [any] $10^{g/20}$.
:::
:::

::: check
given: f1 = 10 | 100; f2 = 1000 | 100000
answer: log(f2/f1)
tolerance: 0.5%

## How many decades are there from {f1} Hz to {f2} Hz?

::: misses
- [any] $\log_{10}(f_2/f_1)$.
:::
:::
:::
