---
title: Solving Ax = b
heading: Writing a circuit as a matrix and letting the computer solve it
eyebrow: A7 · Lesson 12 · Solving Ax = b
xp: 40
---

::: hook
A resistor ladder with three junctions is about as far as most people go by hand. Real circuits have hundreds of nodes, and their equations are solved the same way every time: write the conductance matrix by inspection, write the vector of injected currents, and hand both to a solver. This lesson is that recipe, in code.
:::

::: predict
## To solve $G\mathbf{v} = \mathbf{i}$ in code, which is better: `np.linalg.solve(G, i)` or `np.linalg.inv(G) @ i`?

- [ ] They're identical in every way
- [x] `solve`: it's faster and more accurate, because it never forms the inverse
- [ ] `inv`: inverting is always more accurate
- [ ] Neither works for circuits

::: reveal
`solve`. It runs elimination once on this right-hand side, about $\tfrac23n^3$ operations, while forming the full inverse costs about three times as much and loses more accuracy to rounding. Numerical code almost never computes an inverse explicitly; "multiply by $A^{-1}$" on paper means "solve with $A$" in code.
:::
:::

::: nameit
## The recipe for a resistor circuit

1. **Pick a ground** node and number the others 1 to n.
2. **Build $G$ by inspection:** each diagonal entry $G_{kk}$ is the sum of the conductances touching node $k$; each off-diagonal entry $G_{jk}$ is minus the conductance joining $j$ and $k$ (zero if they aren't joined). $G$ is symmetric.
3. **Build $\mathbf{i}$:** the current pushed into each node by current sources. A voltage source in series with a resistor $R$ can be swapped for a current source $V/R$ in parallel with $R$ (A source transformation, C1), which is how the ladder below gets its right-hand side.
4. **Solve** $G\mathbf{v} = \mathbf{i}$ for the node voltages.
5. **Check:** compute the residual $G\mathbf{v} - \mathbf{i}$, which should be zero to rounding error, and branch currents from voltage differences.

For a ladder fed by $V_s$ through $R_1$, with shunt resistors $R_2$, $R_4$, $R_6$ to ground at nodes 1, 2, 3 and series resistors $R_3$ (1 to 2) and $R_5$ (2 to 3):

$$G = \begin{bmatrix} \frac1{R_1} + \frac1{R_2} + \frac1{R_3} & -\frac1{R_3} & 0 \\ -\frac1{R_3} & \frac1{R_3} + \frac1{R_4} + \frac1{R_5} & -\frac1{R_5} \\ 0 & -\frac1{R_5} & \frac1{R_5} + \frac1{R_6} \end{bmatrix} \qquad \mathbf{i} = \begin{bmatrix} V_s/R_1 \\ 0 \\ 0 \end{bmatrix}$$

The zeros in the corners are typical: each node touches only a few others, so real conductance matrices are mostly zeros (**sparse**), and simulators store and solve them in ways that skip the zeros.
:::

::: example
## A two-node circuit has $G = \begin{bmatrix}3 & -1\\-1 & 2\end{bmatrix}$ mS and $\mathbf{i} = (10, 0)$ mA. Find $\mathbf{v}$.

::: solution
1. **Determinant.**
   $$\begin{aligned} \det G &= 6 - 1 \\ &= 5 \end{aligned}$$
2. **Inverse.**
   $$G^{-1} = \frac{1}{5}\begin{bmatrix}2 & 1\\1 & 3\end{bmatrix}\ \text{k}\Omega$$
3. **Multiply.**
   $$\begin{aligned} \mathbf{v} &= \frac{1}{5}(20, 10) \\ &= (4, 2)\ \text{V} \end{aligned}$$
4. **In NumPy.** `np.linalg.solve(G, i)` with $G$ in mS and $\mathbf{i}$ in mA gives the same numbers in volts.

**Answer:** $\mathbf{v} = (4, 2)$ V.
:::
:::

::: example
## For a 1000 × 1000 system, how does `solve` compare with `inv(G) @ i`?

::: solution
1. **Cost of `solve`.** It factors once, about
   $$\frac{n^3}{3} \approx 3 \times 10^8\ \text{operations}$$
2. **Cost of the inverse.** Forming the inverse takes about $n^3 = 10^9$, three times as much, and then a multiplication on top.
3. **Accuracy.** The inverse is also less accurate.

**Answer:** `solve` wins on both counts: about a third of the work, and a more accurate answer.
:::
:::

::: example
## A three-node ladder has $G = \begin{bmatrix}2 & -1 & 0\\-1 & 2 & -1\\0 & -1 & 2\end{bmatrix}$ mS, with 1 mA injected at node 1. Find the node voltages.

::: solution
1. **Eliminate below the first pivot.** Solving $G\mathbf{v} = (1, 0, 0)$, row 2 + ½ row 1 gives
   $$1.5v_2 - v_3 = 0.5$$
2. **Eliminate below the second.** Row 3 + ⅔ of that gives
   $$\frac43v_3 = \frac13$$
3. **Back-substitute.** $v_3$ = 0.25 V, $v_2$ = 0.5 V and $v_1$ = 0.75 V.
4. **The pattern.** The voltage falls by a quarter volt per node along the ladder. In Python, `np.linalg.solve(G, [1, 0, 0])` gives the same three numbers.

**Answer:** $v_1$ = 0.75 V, $v_2$ = 0.5 V and $v_3$ = 0.25 V.
:::
:::

::: check
kind: python
given: R = 1k..10k E12 Ω

## Build `G` for the ladder above with all six resistors equal to `R` = {R} and $V_s$ = 10 V, build `i`, and solve for `v`, the three node voltages.

```python starter
import numpy as np

g = 1 / R
G = np.zeros((3, 3))   # fill this in
i = np.zeros(3)        # fill this in
v = np.zeros(3)        # replace: solve G v = i
print(v)
```

```python solution
import numpy as np

g = 1 / R
G = np.array([[3 * g, -g, 0],
              [-g, 3 * g, -g],
              [0, -g, 2 * g]])
i = np.array([10 / R, 0, 0])
v = np.linalg.solve(G, i)
print(v)
```

```python tests
import numpy as np
g = 1 / R
G2 = np.array([[3 * g, -g, 0], [-g, 3 * g, -g], [0, -g, 2 * g]])
want = np.linalg.solve(G2, np.array([10 / R, 0, 0]))
assert np.allclose(np.asarray(G, float), G2), "Check G: each diagonal entry adds the conductances touching that node (three at nodes 1 and 2, two at node 3), and each off-diagonal is minus the conductance joining two nodes."
assert np.allclose(np.asarray(i, float), [10 / R, 0, 0]), "i should be [Vs/R1, 0, 0]: only node 1 is fed, through R1."
assert np.allclose(v, want), "v should be the solution of G v = i."
assert abs(v[0] - 50 / 13) < 1e-9, "With equal resistors, V1 should be 50/13 ≈ 3.85 V."
```

::: right
Right. With equal resistors the voltages are 50/13, 20/13 and 10/13 V: about 3.85, 1.54 and 0.77 V, the same whatever R is, since only ratios of resistances matter.
:::
:::

::: check
kind: python
given: R1 = 1k..10k E12 Ω; R2 = 1k..10k E12 Ω; R3 = 1k..10k E12 Ω; R4 = 1k..10k E12 Ω; R5 = 1k..10k E12 Ω; R6 = 1k..10k E12 Ω

## Now with all six resistors different (they're defined as `R1` to `R6`) and $V_s$ = 10 V: solve for `v`, then set `I3` to the current through $R_3$ from node 1 to node 2, and `resid` to the largest absolute entry of $G\mathbf{v} - \mathbf{i}$.

```python starter
import numpy as np

G = np.zeros((3, 3))
i = np.zeros(3)
v = np.zeros(3)
I3 = 0
resid = 0
print(v, I3, resid)
```

```python solution
import numpy as np

g = [1 / R for R in (R1, R2, R3, R4, R5, R6)]
G = np.array([[g[0] + g[1] + g[2], -g[2], 0],
              [-g[2], g[2] + g[3] + g[4], -g[4]],
              [0, -g[4], g[4] + g[5]]])
i = np.array([10 / R1, 0, 0])
v = np.linalg.solve(G, i)
I3 = (v[0] - v[1]) / R3
resid = np.max(np.abs(G @ v - i))
print(v, I3, resid)
```

```python tests
import numpy as np
g = [1 / R for R in (R1, R2, R3, R4, R5, R6)]
G2 = np.array([[g[0] + g[1] + g[2], -g[2], 0], [-g[2], g[2] + g[3] + g[4], -g[4]], [0, -g[4], g[4] + g[5]]])
want = np.linalg.solve(G2, np.array([10 / R1, 0, 0]))
assert np.allclose(v, want), "v doesn't match the ladder's node voltages yet. Build G from the six conductances."
assert abs(I3 - (want[0] - want[1]) / R3) < 1e-12, "I3 is the voltage across R3, (v[0] − v[1]), divided by R3."
assert resid < 1e-12, "resid should be tiny: the largest of |G v − i|."
```

::: right
Right. A residual near $10^{-16}$ amps is the solver telling you the answer satisfies every node's current law to rounding error.
:::
:::

::: check
given: a = 2 | 4; b = 1; c = 1 | 2; d = 3 | 5; x = 1 | 3; y = 2 | 4; let p = a*x + b*y; let q = c*x + d*y
answer: (d*p - b*q)/(a*d - b*c)
tolerance: 0.5%

## Use the 2 × 2 inverse to solve $\begin{bmatrix} \given{a} & \given{b} \\ \given{c} & \given{d} \end{bmatrix}\begin{bmatrix} x \\ y \end{bmatrix} = \begin{bmatrix} \given{p} \\ \given{q} \end{bmatrix}$ for $x$.

::: right
Right. $x = (dp - bq)/(ad - bc)$ = {answer}.
:::

::: misses
- [(a*q - c*p)/(a*d - b*c)] That's y.
- [p/a] The equations are coupled: y matters in the first one too.
- [any] Not yet. Multiply by the inverse: the first row of $\frac{1}{ad - bc}\begin{bmatrix} d & -b \\ -c & a \end{bmatrix}$ times the right-hand side.
:::
:::

::: check
kind: parts
given: g = 1 | 2 | 5; i = 1 | 3

## A circuit has $G = \begin{bmatrix}\given{g} + 1 & -1\\-1 & 2\end{bmatrix}$ mS, with {i} mA injected at node 1.

::: part
answer: 2*i/(2*g + 1)
unit: V
tolerance: 0.5%

### What is $v_1$?

::: misses
- [i/(g + 1)] That ignores node 2.
- [any] $\det G = 2g + 1$; Cramer gives $v_1 = \frac{2i}{2g + 1}$.
:::
:::

::: part
answer: i/(2*g + 1)
unit: V
tolerance: 0.5%

### What is $v_2$?

::: misses
- [any] From row 2: $v_2 = v_1/2$.
:::
:::
:::

::: check
kind: derivation
vars: g = 0.5..5

## Node 1 has $g$ mS to ground and 1 mS to node 2; node 2 has 1 mS to ground; 1 mA flows into node 1.

::: step
answer: 2*g + 1

### $G = \begin{bmatrix}g + 1 & -1\\-1 & 2\end{bmatrix}$. What is $\det G$?
:::

::: step
answer: 1/(2*g + 1)

### What is $v_2$, in volts?
:::

::: right
Right. $v_2 = \frac{1}{2g + 1}$ V: the bigger $g$, the more current goes straight to ground.
:::
:::

::: check
given: I = 1 | 2 | 5; k = 2 | 3; m = 1 | 2 | 3
answer: I*((m + k - abs(m - k))/2)*(4 - (m + k + abs(m - k))/2)/4
unit: V
tolerance: 0.5%

## The three-node ladder above, $G = \begin{bmatrix}2 & -1 & 0\\-1 & 2 & -1\\0 & -1 & 2\end{bmatrix}$ mS, has $G^{-1} = \frac14\begin{bmatrix}3 & 2 & 1\\2 & 4 & 2\\1 & 2 & 3\end{bmatrix}$ kΩ. With {I} mA injected at node {k} and nothing else, what is the voltage at node {m}?

::: right
Right. A current at node {k} alone makes $\mathbf{v}$ equal to {I} mA times column {k} of $G^{-1}$, so node {m} gets {I} × entry ({m}, {k}) = {answer}.
:::

::: misses
- [I*((m + k - abs(m - k))/2)*(4 - (m + k + abs(m - k))/2)] Don't forget the $\frac14$ in front of the inverse.
- [any] Not yet. $\mathbf{v} = G^{-1}\mathbf{i}$, and $\mathbf{i}$ has {I} mA only in position {k}: read off row {m} of column {k}.
:::
:::

::: explain
## Why does a circuit with n nodes (besides ground) give an n × n conductance matrix?

::: model
Each non-ground node has one unknown voltage and one current-law equation: the currents leaving it add to zero. Each equation involves that node's voltage and the voltages of the nodes it connects to, so stacking the n equations gives n rows, and each row has one column per unknown voltage: an n × n matrix times the vector of n node voltages.
:::
:::

::: practice

::: check
kind: python
given: g1 = 1..5 int; g2 = 1..5 int; g3 = 1..5 int

## Two nodes: node 1 has conductances {g1} S to ground and {g2} S to node 2; node 2 has {g3} S to ground. 1 A is injected into node 1. Solve for `v` (two voltages).

```python starter
import numpy as np

v = np.zeros(2)
print(v)
```

```python solution
import numpy as np

G = np.array([[g1 + g2, -g2], [-g2, g2 + g3]], dtype=float)
v = np.linalg.solve(G, np.array([1.0, 0.0]))
print(v)
```

```python tests
import numpy as np
G = np.array([[g1 + g2, -g2], [-g2, g2 + g3]], dtype=float)
assert np.allclose(v, np.linalg.solve(G, [1.0, 0.0])), "Build G (diagonals: total conductance at each node; off-diagonals: minus the joining conductance) and solve with i = [1, 0]."
```
:::

::: check
given: a = 3 | 5 | 7 | 9; b = 2 | 4
answer: 1/(a*a - b*b)*a
tolerance: 0.5%

## What is the top-left entry of the inverse of the symmetric matrix $\begin{bmatrix} \given{a} & \given{b} \\ \given{b} & \given{a} \end{bmatrix}$?

::: misses
- [1/a] Invert the matrix as a whole: $\frac{1}{a^2 - b^2}\begin{bmatrix} a & -b \\ -b & a \end{bmatrix}$.
- [any] Use the 2 × 2 inverse formula.
:::
:::
:::
