---
title: "Lab: functions and equations in Python"
heading: Letting the computer find the answer algebra can't
eyebrow: A2 · Lesson 13 · Lab: functions and equations
xp: 60
---

::: hook
Every equation in this course so far had an answer you could write down. Real circuits soon produce ones that don't, such as a diode's exponential in series with a resistor. Then engineers let a computer close in on the answer step by step. In this lab you'll write four small Python tools that do that kind of work: a piecewise function, an interval-halving solver, a line through two points, and a loop that adds up a series. If you haven't started A4 yet, its lessons on functions, if, loops and lists (lessons 1 to 9) cover all the Python used here.
:::

::: play
- The curve is $f(t) = 5(1 - e^{-t/\tau}) - 3.3$ with $\tau$ = 10 ms: a capacitor charging toward 5 V, minus the 3.3 V it has to reach. The answer is where the curve crosses zero.
- The two markers are the ends of the bracket where the solver is still looking. Each step cuts the bracket in half and keeps the half whose ends have opposite signs.
- Step it up and watch the bracket close in. How many steps until it's narrower than a microsecond?
:::

```sim plot
view: graph
x: t = 0..30m s
y: f = -3.5..2 V
slider: k = 0..20 step 1 = 0
plot: 5*(1 - exp(-t/0.01)) - 3.3 | samples: 300 | label: f(t)
marker: t = 0.03*floor(0.01*ln(5/1.7)/0.03*2^k)/2^k | label: a
marker: t = 0.03*floor(0.01*ln(5/1.7)/0.03*2^k)/2^k + 0.03/2^k | label: b
readout: bracket width, µs = 0.03/2^k*1e6 | digits: 4
readout: exact answer, ms = 0.01*ln(5/1.7)*1000 | digits: 6
```

::: predict
## The bracket starts 30 ms wide and halves at every step. About how many steps does it take to get it under 1 µs?

- [ ] 5
- [x] 15
- [ ] 30
- [ ] 30 000

::: reveal
It takes 15. The bracket has to shrink by a factor of $30\ \text{ms} / 1\ \mu\text{s} = 30\,000$, and $2^{15}$ = 32 768 is the first power of two past that. Each step pins down one more binary digit of the answer, or about 3.3 steps per decimal digit. That's slow next to the methods you'll meet in calculus, but it can't fail once the bracket holds a sign change.
:::
:::

::: nameit
## Functions in Python

A Python function takes some values and returns a result. Inside, `if`, `elif` and `else` pick between cases, which is all a piecewise function needs:

```python
def clip(x, lo, hi):
    if x < lo:
        return lo
    elif x > hi:
        return hi
    else:
        return x
```

A function can also take another function as a value. That's how one solver can work on any equation: you hand it the function whose zero you want.

## Bisection

If $f$ is continuous and $f(a)$ and $f(b)$ have opposite signs, the graph must cross zero somewhere between them. Bisection keeps halving that bracket:

1. Find the midpoint $m = (a + b)/2$.
2. If $f(a)$ and $f(m)$ have opposite signs (or $f(m) = 0$), the crossing is in $[a, m]$, so set $b = m$. Otherwise it's in $[m, b]$, so set $a = m$.
3. Repeat until $b - a$ is smaller than the tolerance you want.

After $n$ steps the bracket is $(b - a)/2^n$ wide, so reaching a width $w$ takes $\lceil \log_2((b - a)/w) \rceil$ steps.

## Lines from points

The line through $(x_1, y_1)$ and $(x_2, y_2)$ has slope $m = \frac{y_2 - y_1}{x_2 - x_1}$ and intercept $c = y_1 - mx_1$. Two lines $y = m_1x + c_1$ and $y = m_2x + c_2$ meet where $m_1x + c_1 = m_2x + c_2$:

$$x = \frac{c_2 - c_1}{m_1 - m_2}$$

## Sums with a loop

A loop adds terms one at a time:

```python
total = 0
for k in range(n):
    total = total + a * r**k
```

For a geometric series you can check the loop against $a\frac{1 - r^n}{1 - r}$. For most series there's no formula, and the loop is the only way.
:::

::: example
## Run three steps of bisection on $f(t) = 5(1 - e^{-t/0.01}) - 3.3$, starting from $[0, 30\ \text{ms}]$.

::: solution
1. **Check the bracket.** $f(0) = -3.3$ is negative and $f(30\ \text{ms}) = 1.45$ is positive, so there's a crossing between.
2. **First midpoint, 15 ms.**
   $$\begin{aligned} f &= 5(1 - e^{-1.5}) - 3.3 \\ &= 0.584 \end{aligned}$$
   It's positive, so keep $[0, 15]$ ms.
3. **Second midpoint, 7.5 ms.**
   $$\begin{aligned} f &= 5(1 - e^{-0.75}) - 3.3 \\ &= -0.662 \end{aligned}$$
   It's negative, so keep $[7.5, 15]$ ms.
4. **Third midpoint, 11.25 ms.**
   $$\begin{aligned} f &= 5(1 - e^{-1.125}) - 3.3 \\ &= 0.077 \end{aligned}$$
   It's positive, so keep $[7.5, 11.25]$ ms.
5. **Compare with the exact answer.** It's inside the final bracket, which is now 3.75 ms wide:
   $$10\ \text{ms} \times \ln(5/1.7) = 10.788\ \text{ms}$$

**Answer:** after three steps the crossing is in $[7.5, 11.25]$ ms, which holds the exact answer, 10.788 ms.
:::
:::

::: example
## A 5 V source drives a 1 kΩ resistor in series with a diode whose current is $I = 10^{-14}(e^{V/0.025\,85} - 1)$ A. What voltage is across the diode?

::: solution
1. **Match the currents.** The resistor's current and the diode's current must match:
   $$\begin{aligned} f(V) &= \frac{5 - V}{1000} \\ &\quad - 10^{-14}\left(e^{V/0.025\,85} - 1\right) \\ &= 0 \end{aligned}$$
2. **Choose a method.** No algebra will free $V$ from inside the exponential and the line at once.
3. **Bracket the root.** $f(0) = 0.005$ is positive and $f(1)$ is hugely negative, so bisection on $[0, 1]$ works.
4. **Bisect.** Twenty steps narrow the bracket below 1 µV, at $V = 0.6925$ V.
5. **Current.**
   $$\begin{aligned} I &= \frac{5 - 0.6925}{1000}\ \text{A} \\ &= 4.31\ \text{mA} \end{aligned}$$

**Answer:** the diode has 0.6925 V across it, with 4.31 mA flowing.
:::
:::

::: example
## A battery reads 12.6 V with no load and 12.1 V at 10 A. Where does its line cross the line of a 1.2 Ω load?

::: solution
1. **The battery's line.** Through (0 A, 12.6 V) and (10 A, 12.1 V), the slope is $-0.5/10 = -0.05$ V/A, so
   $$V = 12.6 - 0.05I$$
2. **The load's line.**
   $$V = 1.2I$$
3. **Set them equal.**
   $$\begin{aligned} 12.6 - 0.05I &= 1.2I \\ I &= \frac{12.6}{1.25} \\ &= 10.08\ \text{A} \end{aligned}$$
4. **Voltage.**
   $$\begin{aligned} V &= 1.2 \times 10.08 \\ &= 12.10\ \text{V} \end{aligned}$$
5. **In the lab.** That crossing is the operating point, and `intersect` finds it from the two slopes and intercepts.

**Answer:** the lines cross at 10.08 A and 12.10 V, which is the operating point.
:::
:::

::: check
given: W = 10 | 30 | 100; w = 1 | 10 | 100
answer: ceil(log(W*1e-3/(w*1e-6))/log(2))
tolerance: 0

## Bisection starts with a bracket {W} ms wide. How many steps until the bracket is no wider than {w} µs?

::: right
Right. The bracket must shrink by $\given{W}\ \text{ms}/\given{w}\ \mu\text{s}$, and each step halves it: {answer} steps.
:::

::: misses
- [floor(log(W*1e-3/(w*1e-6))/log(2))] One step short: after that many halvings the bracket is still a little wider than {w} µs.
- [W*1e-3/(w*1e-6)] That's the factor it must shrink by. Count the halvings instead.
- [any] Not yet. Find $n$ with $2^n$ at least the ratio of the widths.
:::
:::

::: check
given: a = 0 | 1 | 2; b = 4 | 6 | 10
answer: (a + b)/2 + (b - a)/4
tolerance: 0.5%

## Bisection on $[\given{a}, \given{b}]$ finds that $f$ at the midpoint has the same sign as $f(\given{a})$. Where is the next midpoint?

::: right
Right. The crossing is in the right half, $[(a + b)/2, b]$, whose midpoint is {answer}.
:::

::: misses
- [(a + b)/2 - (b - a)/4] That's the midpoint of the left half. The same sign as $f(a)$ means the crossing isn't in $[a, m]$.
- [(a + b)/2] That's the first midpoint.
- [any] Not yet. Keep the half whose ends have opposite signs, then take its midpoint.
:::
:::

::: check
kind: python

## Write `clip(x, lo, hi)`: it returns `lo` when `x` is below `lo`, `hi` when `x` is above `hi`, and `x` otherwise. This is an amplifier that can't swing past its supply rails.

```python starter
def clip(x, lo, hi):
    return x

print(clip(5, -12, 12), clip(20, -12, 12), clip(-15, -12, 12))
```

```python solution
def clip(x, lo, hi):
    if x < lo:
        return lo
    elif x > hi:
        return hi
    else:
        return x

print(clip(5, -12, 12), clip(20, -12, 12), clip(-15, -12, 12))
```

```python tests
assert clip(5, -12, 12) == 5, "Inside the rails, the output should follow the input."
assert clip(20, -12, 12) == 12, "Above the top rail, the output should be stuck at hi."
assert clip(-15, -12, 12) == -12, "Below the bottom rail, the output should be stuck at lo."
assert clip(12, -12, 12) == 12 and clip(0, 0, 5) == 0, "Values exactly at a rail should come out unchanged."
gain = [clip(10 * v, -12, 12) for v in (-2, -0.5, 0.3, 1.5)]
assert gain == [-12, -5, 3, 12], f"A gain of 10 into rails at ±12 V should give [-12, -5, 3, 12]; got {gain}."
```

::: right
Right. Feeding it `10 * v` gives the whole clipping amplifier from the piecewise lesson.
:::
:::

::: check
kind: python

## Write `bisect(f, a, b, tol)`. It assumes `f(a)` and `f(b)` have opposite signs, halves the bracket until it's narrower than `tol`, and returns the midpoint of the final bracket. The tests use it on the capacitor and the diode from the examples.

```python starter
import math

def bisect(f, a, b, tol):
    return (a + b) / 2

def charge(t):
    return 5 * (1 - math.exp(-t / 0.01)) - 3.3

print(bisect(charge, 0, 0.03, 1e-9))
```

```python solution
import math

def bisect(f, a, b, tol):
    fa = f(a)
    while b - a > tol:
        m = (a + b) / 2
        fm = f(m)
        if fa * fm <= 0:
            b = m
        else:
            a, fa = m, fm
    return (a + b) / 2

def charge(t):
    return 5 * (1 - math.exp(-t / 0.01)) - 3.3

print(bisect(charge, 0, 0.03, 1e-9))
```

```python tests
import math
t = bisect(lambda t: 5 * (1 - math.exp(-t / 0.01)) - 3.3, 0, 0.03, 1e-9)
assert abs(t - 0.01 * math.log(5 / 1.7)) < 1e-9, f"The capacitor reaches 3.3 V at 10.788 ms; got {t * 1000:.6f} ms."
v = bisect(lambda v: (5 - v) / 1000 - 1e-14 * (math.exp(v / 0.02585) - 1), 0, 1, 1e-9)
assert abs(v - 0.69249) < 1e-5, f"The diode should sit near 0.6925 V; got {v:.6f} V."
r = bisect(lambda x: x * x - 2, 0, 2, 1e-12)
assert abs(r - math.sqrt(2)) < 1e-11, "It should find the square root of 2 on [0, 2]."
r = bisect(lambda x: 2 - x * x, 0, 2, 1e-12)
assert abs(r - math.sqrt(2)) < 1e-11, "It should also work when f starts positive and ends negative."
```

::: right
Right. The same twelve lines solve any equation you can bracket, from a capacitor's timing to a diode's operating point.
:::
:::

::: check
kind: python

## Write `line_through(x1, y1, x2, y2)`, returning the slope and intercept `(m, c)`, and `intersect(m1, c1, m2, c2)`, returning the point `(x, y)` where two lines meet. The test finds a battery's line from two readings and crosses it with a load's line.

```python starter
def line_through(x1, y1, x2, y2):
    return 0, 0

def intersect(m1, c1, m2, c2):
    return 0, 0

m, c = line_through(0, 12.6, 10, 12.1)
print(m, c)
```

```python solution
def line_through(x1, y1, x2, y2):
    m = (y2 - y1) / (x2 - x1)
    return m, y1 - m * x1

def intersect(m1, c1, m2, c2):
    x = (c2 - c1) / (m1 - m2)
    return x, m1 * x + c1

m, c = line_through(0, 12.6, 10, 12.1)
print(m, c)
```

```python tests
m, c = line_through(0, 12.6, 10, 12.1)
assert abs(m + 0.05) < 1e-12 and abs(c - 12.6) < 1e-12, f"The battery's line should be V = 12.6 - 0.05 I; got slope {m}, intercept {c}."
m2, c2 = line_through(2, 5, 6, 13)
assert abs(m2 - 2) < 1e-12 and abs(c2 - 1) < 1e-12, "The line through (2, 5) and (6, 13) is y = 2x + 1."
# A 1.2 ohm load: V = 1.2 I. Where does it cross the battery's line?
x, y = intersect(m, c, 1.2, 0)
assert abs(x - 12.6 / 1.25) < 1e-9 and abs(y - 1.2 * 12.6 / 1.25) < 1e-9, f"The battery and a 1.2 ohm load should meet at 10.08 A, 12.096 V; got ({x}, {y})."
```

::: right
Right. The crossing is the operating point: the one current and voltage that suit both the battery and the load.
:::
:::

::: check
kind: python

## Write `geometric_sum(a, r, n)`, which adds the first `n` terms $a, ar, ar^2, \ldots$ with a loop, and `steps_within(r, frac)`, which returns the smallest whole number $n$ with $r^n \le$ `frac`. A capacitor charged in steps that each close a share of the remaining gap follows exactly these.

```python starter
def geometric_sum(a, r, n):
    return 0

def steps_within(r, frac):
    return 0

print(geometric_sum(1, 0.9, 20), steps_within(0.8, 0.01))
```

```python solution
def geometric_sum(a, r, n):
    total = 0
    for k in range(n):
        total = total + a * r**k
    return total

def steps_within(r, frac):
    n = 0
    while r**n > frac:
        n = n + 1
    return n

print(geometric_sum(1, 0.9, 20), steps_within(0.8, 0.01))
```

```python tests
s = geometric_sum(1, 0.9, 20)
assert abs(s - (1 - 0.9**20) / 0.1) < 1e-12, f"The first 20 terms of 1 + 0.9 + 0.81 + ... make 8.784; got {s}."
assert abs(geometric_sum(3, 0.5, 5) - 5.8125) < 1e-12, "3 + 1.5 + 0.75 + 0.375 + 0.1875 = 5.8125."
assert geometric_sum(2, 0.5, 0) == 0, "Zero terms add up to zero."
assert steps_within(0.8, 0.01) == 21, f"0.8^21 is the first power of 0.8 at or below 0.01; got {steps_within(0.8, 0.01)}."
assert steps_within(0.5, 0.25) == 2 and steps_within(0.9, 1) == 0, "Count the first n where r^n reaches frac, starting from n = 0."
```

::: right
Right. A loop like this adds up any series, including the many with no tidy formula.
:::
:::

::: explain
## Bisection never fails on a bracketed root, yet it's slow. Explain both: why it always works, and why each step gains so little.

::: model
It always works because of continuity. If $f$ is continuous and has opposite signs at the two ends of an interval, its graph has to cross zero somewhere inside. Each step checks the midpoint and keeps whichever half still has opposite signs at its ends, so the crossing is never lost, whatever the function looks like between the points. It's slow because each step uses only the sign of $f$ at the midpoint and throws away its size. That one bit of information halves the bracket, so each step adds one binary digit to the answer, about 3.3 steps for every decimal digit. Methods that also use how steep the curve is, like Newton's method in calculus, can double the number of correct digits at each step, but they can fail when started badly.
:::
:::

::: practice

::: check
given: W = 1..1000; w = 0.001..1
answer: ceil(log(W/w)/log(2))
tolerance: 0

## Bisection: a bracket {W} wide, target width {w}. How many steps?

::: misses
- [any] The smallest $n$ with $2^n \ge \given{W}/\given{w}$.
:::
:::

::: check
given: x1 = -5..5 int; y1 = -10..10 int; x2 = 6..12 int; y2 = 11..20 int
answer: (y2 - y1)/(x2 - x1)
tolerance: 0.5%

## Slope of the line through $(\given{x1}, \given{y1})$ and $(\given{x2}, \given{y2})$?

::: misses
- [any] Rise over run.
:::
:::
:::
