---
title: Solving equations numerically
heading: When the algebra runs out, let the computer search
eyebrow: A4 · Lesson 37 · Solving equations numerically
xp: 40
---

::: hook
Where does $\cos x = x$? There's no formula for it: no amount of algebra will isolate $x$. Equations like that are everywhere in electronics, from a diode's current to the frequency where a filter's gain crosses some level. A computer finds the answer to twelve digits in microseconds, by searching in a way that's guaranteed to close in on it.
:::

::: predict
## Bisection keeps halving an interval that contains a root. Starting from an interval 1 wide, roughly how many halvings until it's narrower than a millionth?

- [ ] 6
- [x] 20
- [ ] 1000
- [ ] A million

::: reveal
About 20. Each halving divides the width by 2, and $2^{20} \approx 1.05 \times 10^{6}$, so twenty halvings take it below a millionth. That's the power of halving: each step adds about a third of a decimal digit, so twelve digits takes about forty steps.
:::
:::

::: nameit
## Three tools for three kinds of equation

**Bisection, for any one equation in one unknown.** Write the equation as $f(x) = 0$. If $f(a)$ and $f(b)$ have opposite signs and $f$ is continuous, a root lies between them. Check the midpoint, keep the half where the sign still changes, and repeat:

```
def bisect(f, a, b, tol=1e-12):
    fa = f(a)
    while b - a > tol:
        m = (a + b) / 2
        fm = f(m)
        if (fm > 0) == (fa > 0):   # same sign as f(a): the root is in [m, b]
            a, fa = m, fm
        else:                      # the root is in [a, m]
            b = m
    return (a + b) / 2
```

It's slow compared with cleverer methods, but it can't fail once the root is bracketed. Libraries like SciPy offer faster ones (`scipy.optimize.brentq`) built on the same idea.

**Roots of a polynomial.** `np.roots(coefficients)` returns every root, complex ones included, from the coefficients in order of falling power. For $x^3 - 3x - 1$: `np.roots([1, 0, -3, -1])`.

**Linear systems.** Several unknowns linked by linear equations, like

$$\begin{aligned} 3x + 2y &= 7 \\ x - y &= -1 \end{aligned}$$

are written as a matrix times a vector: $\begin{bmatrix} 3 & 2 \\ 1 & -1 \end{bmatrix}\begin{bmatrix} x \\ y \end{bmatrix} = \begin{bmatrix} 7 \\ -1 \end{bmatrix}$, and solved with

```
A = np.array([[3, 2], [1, -1]])
b = np.array([7, -1])
x, y = np.linalg.solve(A, b)     # x = 1, y = 2
```

This is how circuit simulators work: Kirchhoff's laws give one linear equation per node, and the solver handles hundreds of them at once. You'll write those equations yourself in C1; A7 explains what the solver does inside.
:::

::: example
## Solve a two-node circuit: 5 V through 1 kΩ into node 1, 2 kΩ from node 1 to node 2, 4 kΩ from node 2 to ground, nothing else.

::: solution
1. **Write KCL at each node, with conductances, and solve.** The 5 V source through 1 kΩ drives 5 mA into node 1.

```
import numpy as np
G = np.array([[1/1e3 + 1/2e3, -1/2e3],
              [-1/2e3,        1/2e3 + 1/4e3]])
i = np.array([5/1e3, 0])
print(np.linalg.solve(G, i))     # [4.2857 2.8571]
```

2. **Check by hand.** It's a series string of 7 kΩ, so 0.714 mA flows, and node 2 is
   $$\begin{aligned} v_2 &= 0.714 \times 4\ \text{V} \\ &= 2.857\ \text{V} \end{aligned}$$

**Answer:** node 1 is at 4.286 V and node 2 at 2.857 V.
:::
:::

::: example
## Find the roots of $s^2 + 3s + 2$ and $s^2 + 2s + 5$.

::: solution
1. **Pass the coefficients to `np.roots`.**

```
print(np.roots([1, 3, 2]))       # [-2. -1.]
print(np.roots([1, 2, 5]))       # [-1.+2.j -1.-2.j]
```

2. **The first polynomial.** Its roots are −2 and −1: the first circuit settles with two real decays.
3. **The second polynomial.** Its roots are $-1 \pm 2j$: the second rings, with the complex pair from A3.

**Answer:** $s^2 + 3s + 2$ has roots −2 and −1, and $s^2 + 2s + 5$ has roots $-1 \pm 2j$.
:::
:::

::: check
kind: python

## Write `bisect(f, a, b)` that returns a root of `f` between `a` and `b` to within $10^{-9}$, assuming `f(a)` and `f(b)` have opposite signs. Then use it to set `x` to the solution of $\cos x = x$.

```python starter
import math

def bisect(f, a, b):
    return a   # replace this

x = bisect(lambda x: math.cos(x) - x, 0, 1)
print(x)
```

```python solution
import math

def bisect(f, a, b):
    fa = f(a)
    while b - a > 1e-10:
        m = (a + b) / 2
        fm = f(m)
        if (fm > 0) == (fa > 0):
            a, fa = m, fm
        else:
            b = m
    return (a + b) / 2

x = bisect(lambda x: math.cos(x) - x, 0, 1)
print(x)
```

```python tests
import math
r = bisect(lambda t: t**2 - 2, 0, 2)
assert abs(r - math.sqrt(2)) < 1e-8, "bisect(lambda t: t**2 - 2, 0, 2) should find √2 ≈ 1.41421356."
r2 = bisect(lambda t: 1 - t, 0, 3)
assert abs(r2 - 1) < 1e-8, "Your bisect should also work when f falls from positive to negative: bisect(lambda t: 1 - t, 0, 3) should give 1."
assert abs(x - 0.7390851332) < 1e-8, "x should be about 0.739085, where cos x = x."
```

::: right
Right. $x \approx 0.739085$, found by nothing cleverer than halving.
:::
:::

::: check
kind: python
given: a = 2..6 int; b = 1..9 int

## Use `np.roots` to find all three roots of $x^3 - \given{a}x - \given{b}$, and set `r` to them sorted from smallest to largest real part.

```python starter
import numpy as np

r = []
print(r)
```

```python solution
import numpy as np

r = np.sort_complex(np.roots([1, 0, -a, -b]))
print(r)
```

```python tests
import numpy as np
want = np.sort_complex(np.roots([1, 0, -a, -b]))
assert len(r) == 3, "A cubic has three roots. Pass all four coefficients: [1, 0, -a, -b] (the x² term is 0)."
assert np.allclose(np.sort_complex(np.asarray(r, complex)), want), "The roots don't match yet. Check the coefficient list: x³ + 0x² − a·x − b."
```

::: right
Right. Some cubics give three real roots and some one real and a complex pair; `np.roots` returns whichever it is.
:::
:::

::: check
kind: python
given: p = 2..9 int; q = 2..9 int; r = 2..9 int

## Solve this system with `np.linalg.solve` and set `sol` to the array of $x, y, z$:

$$\begin{aligned} \given{p}x + y + z &= 10 \\ x + \given{q}y + z &= 12 \\ x + y + \given{r}z &= 14 \end{aligned}$$

```python starter
import numpy as np

A = np.array([[p, 1, 1], [1, q, 1], [1, 1, r]], dtype=float)
b = np.array([0, 0, 0], dtype=float)   # fix the right-hand sides
sol = np.zeros(3)                      # replace this
print(sol)
```

```python solution
import numpy as np

A = np.array([[p, 1, 1], [1, q, 1], [1, 1, r]], dtype=float)
b = np.array([10, 12, 14], dtype=float)
sol = np.linalg.solve(A, b)
print(sol)
```

```python tests
import numpy as np
A2 = np.array([[p, 1, 1], [1, q, 1], [1, 1, r]], dtype=float)
want = np.linalg.solve(A2, np.array([10, 12, 14], dtype=float))
assert np.allclose(A2 @ np.asarray(sol, float), [10, 12, 14]), "sol doesn't satisfy the three equations yet. Set b to [10, 12, 14] and use np.linalg.solve(A, b)."
assert np.allclose(sol, want), "sol should be the solution of A·x = b."
```

::: right
Right. A circuit simulator does exactly this, with one row per node.
:::
:::

::: check
kind: choice

## You call bisection on $f(x) = x^2 + 1$ between −1 and 1. What happens?

- [ ] It finds the root at 0
- [x] It returns a meaningless point: $f(-1)$ and $f(1)$ have the same sign, so no root is bracketed
- [ ] It finds the complex roots $\pm j$
- [ ] It halves forever

::: right
Right. Bisection's guarantee needs opposite signs at the ends. $x^2 + 1$ is positive everywhere, so there's nothing to find, and a careful version would check the signs first and refuse.
:::

::: misses
- [1] $f(0) = 1$, not 0. This function never touches zero for real x.
- [3] Bisection only searches the real line between a and b.
- [4] The interval still halves each step, so the loop stops; it just stops somewhere meaningless.
:::
:::

::: check
kind: python
given: Vs = 5 | 9 | 12; Vt = 2 | 3.3 | 4; tau = 1 | 4.7 | 10

## A capacitor charges as $v(t) = V_s(1 - e^{-t/\tau})$ with `Vs` = {Vs} V and `tau` = {tau} ms. Write `newton(f, df, x0)`, which repeats $x \leftarrow x - f(x)/f'(x)$ until a step is smaller than $10^{-12}$ and returns $x$. Use it from `x0 = tau` to set `t` to the time in ms when $v$ reaches `Vt` = {Vt} V, and `iters` to how many steps it took.

```python starter
import math

def newton(f, df, x0):
    return x0, 0

t, iters = newton(lambda t: Vs * (1 - math.exp(-t / tau)) - Vt, lambda t: Vs / tau * math.exp(-t / tau), tau)
print(t, iters)
```

```python solution
import math

def newton(f, df, x0):
    x = x0
    n = 0
    while True:
        step = f(x) / df(x)
        x -= step
        n += 1
        if abs(step) < 1e-12:
            return x, n

t, iters = newton(lambda t: Vs * (1 - math.exp(-t / tau)) - Vt, lambda t: Vs / tau * math.exp(-t / tau), tau)
print(t, iters)
```

```python tests
import math
exact = -tau * math.log(1 - Vt / Vs)
assert abs(t - exact) < 1e-9 * exact, f"t should be {exact:.6f} ms, which is -tau * ln(1 - Vt/Vs)."
assert 3 <= iters <= 10, f"Newton should converge in a handful of steps, not {iters}."
```

::: right
Right. This one has a formula, $t = -\tau \ln(1 - V_t/V_s)$, which is how you know Newton got it right. Newton's real job is the equations with no formula, and its speed here, a few steps to twelve digits, is typical.
:::
:::

::: check
kind: choice

## `A = np.array([[1, 2], [2, 4]])` and `b = np.array([3, 6])`. What does `np.linalg.solve(A, b)` do?

- [x] Raises `LinAlgError`, because the matrix is singular
- [ ] Returns `[3, 0]`
- [ ] Returns the least-squares answer
- [ ] Returns `[inf, inf]`

::: right
Right. The second row is twice the first, so the two equations are really one, and there are infinitely many solutions. `solve` needs exactly one and refuses. `np.linalg.lstsq` would pick the smallest solution.
:::

::: misses
- [2] That's one of infinitely many solutions. `solve` won't choose among them; it raises an error.
- [3] That's what `np.linalg.lstsq` does. `solve` requires a matrix with an inverse.
- [4] `solve` checks for a singular matrix and raises an error instead of dividing by zero.
:::
:::

::: explain
## Why is bisection guaranteed to find a root once $f(a)$ and $f(b)$ have opposite signs?

::: model
A continuous function can't get from a negative value to a positive one without passing through zero, so a root lies somewhere between a and b. Each step checks the midpoint and keeps whichever half still has opposite signs at its ends, so the root is always inside the interval. The interval halves every step, so after n steps the root is pinned down to within $(b - a)/2^n$.
:::
:::

::: practice

::: check
kind: python
given: a = 1..9 int; b = 1..9 int; c = 10..30 int; d = 1..9 int

## Solve $\given{a}x + \given{b}y = \given{c}$, $x - y = \given{d}$ with `np.linalg.solve`; set `x` and `y`.

```python starter
import numpy as np

x, y = 0, 0
print(x, y)
```

```python solution
import numpy as np

x, y = np.linalg.solve(np.array([[a, b], [1, -1]], dtype=float), np.array([c, d], dtype=float))
print(x, y)
```

```python tests
assert abs(a * x + b * y - c) < 1e-9 and abs(x - y - d) < 1e-9, "x and y should satisfy both equations."
```
:::

::: check
kind: python
given: V0 = 5..15 int; tau = 1..9 int; th = 0.3..0.9 sig 1

## A capacitor charges as $\given{V0}(1 - e^{-t/\tau})$ with $\tau$ = {tau} ms. Use bisection (write it, or reuse yours) to set `t_hit` to the time, in ms, when it reaches {th} × {V0} V.

```python starter
import math

t_hit = 0
print(t_hit)
```

```python solution
import math

def bisect(f, a, b):
    fa = f(a)
    while b - a > 1e-12:
        m = (a + b) / 2
        fm = f(m)
        if (fm > 0) == (fa > 0):
            a, fa = m, fm
        else:
            b = m
    return (a + b) / 2

t_hit = bisect(lambda t: V0 * (1 - math.exp(-t / tau)) - th * V0, 0, 20 * tau)
print(t_hit)
```

```python tests
import math
assert abs(t_hit - tau * math.log(1 / (1 - th))) < 1e-6 * tau, "t_hit should be where V0·(1 − exp(−t/tau)) equals th·V0. (The exact answer is tau·ln(1/(1 − th)), which you can use to check.)"
```
:::

::: check
kind: python
given: p = -9 | -7 | -5 | 5 | 7 | 9; q = 1..6 int

## Use `np.roots` to find the roots of $x^2 + (\given{p})x + \given{q}$; set `r` to the root with the larger real part.

```python starter
import numpy as np

r = 0
print(r)
```

```python solution
import numpy as np

roots = np.roots([1, p, q])
r = roots[np.argmax(roots.real)]
print(r)
```

```python tests
import numpy as np
roots = np.roots([1, p, q])
assert abs(r - roots[np.argmax(roots.real)]) < 1e-9, "r should be the root of x² + p·x + q with the larger real part."
```
:::
:::
