---
title: "Lab: decisions, loops and functions"
heading: Picking parts, running a thermostat and timing an oscillator in code
eyebrow: A4 · Lesson 10 · Lab: decisions, loops and functions
xp: 60
---

::: hook
Lessons 7 to 9 gave you `if`, loops and functions with defaults and function arguments. On their own they're small; together they're most of what everyday engineering code does. This lab uses them on four jobs: choosing a real resistor and its power rating, running a thermostat over a day of temperatures, timing a relaxation oscillator step by step, and finding where a filter's gain falls to a given level by searching with a function you pass in.
:::

::: predict
## A loop adds 0.001 to `v` two thousand times, starting from 0. Does `v >= 2.0` come out `True`?

- [ ] Yes, `v` is exactly 2.0
- [x] Not necessarily: rounding can leave `v` a hair below 2.0
- [ ] No, `v` is always exactly 1.999
- [ ] It raises an error

::: reveal
Not necessarily. 0.001 has no exact binary form, and two thousand roundings add up: here `v` ends at 1.9999999999998 or so, just below 2.0, so a threshold test fires one step late. Simulations that count steps to a threshold are off by a step now and then for exactly this reason. It rarely matters, but it's why you compare with a tolerance or count with integers when the count itself is the answer.
:::
:::

::: nameit
## Patterns this lab uses

- **Search a list with a condition:** `min(v for v in values if v >= target)` finds the smallest value that's big enough.
- **A loop with state:** keep the variables that carry over (a voltage, whether a heater is on) outside the loop, and update them each pass.
- **Count events:** an `if` inside the loop increments a counter or appends an index when something happens.
- **Pass a function in:** a search written once, `bisect(f, a, b)`, works for any `f`, and a `lambda` builds a small `f` on the spot.
- **Defaults for the usual case:** `sweep(start, stop, n=10, log=False)` gives the common call a short form and the unusual one a keyword.
:::

::: example
## An LED drops 2.0 V and should run at no more than 15 mA from a 5 V supply. Choose the E12 resistor and its power rating, using a rating at least twice the dissipation.

::: solution
1. **Find the ideal resistance.**
   $$\begin{aligned} R &= \frac{5 - 2.0}{0.015}\ \Omega \\ &= 200\ \Omega \end{aligned}$$
2. **Search the E12 values and the ratings.** Take the smallest E12 value at or above the ideal, then the smallest rating at least twice the dissipation.

```python
E12 = [1.0, 1.2, 1.5, 1.8, 2.2, 2.7, 3.3, 3.9, 4.7, 5.6, 6.8, 8.2]
values = [m * 10**d for d in range(7) for m in E12]
ideal = (5 - 2.0) / 0.015                        # 200 Ω
R = min(v for v in values if v >= ideal - 1e-9)  # 220 Ω
I = (5 - 2.0) / R                                # 13.6 mA
P = I**2 * R                                     # 0.0409 W
rating = min(r for r in [0.125, 0.25, 0.5, 1] if r >= 2 * P)
print(R, I, P, rating)                           # 220.0 0.01364 0.0409 0.125
```

3. **Round up to E12.** The ideal 200 Ω isn't an E12 value, so the next one up, 220 Ω, keeps the current under the limit:
   $$\begin{aligned} I &= \frac{3\ \text{V}}{220\ \Omega} \\ &= 13.6\ \text{mA} \end{aligned}$$
4. **Choose the rating.** It dissipates 41 mW, and twice that fits in the smallest common rating, 1/8 W.
5. **Guard the comparison.** The `- 1e-9` guards against an E12 value computed as 149.99999999 being skipped when the ideal is exactly 150.

**Answer:** a 220 Ω resistor rated 1/8 W, which runs the LED at 13.6 mA.
:::
:::

::: example
## A 10 µA current source charges 100 nF. When the voltage reaches 2.0 V a comparator discharges it to zero at once. Simulate 100 ms in 10 µs steps and measure the period.

::: solution
1. **Step the charge and record each reset.** Each step adds $I\,\Delta t/C$ = 1 mV, and the comparator zeroes the voltage at 2.0 V.

```python
C, I, Vth, dt = 100e-9, 10e-6, 2.0, 10e-6
v, resets = 0.0, []
for k in range(10000):
    v += I * dt / C              # 1 mV per step
    if v >= Vth:
        v = 0.0
        resets.append(k)
period = (resets[-1] - resets[0]) / (len(resets) - 1) * dt
print(len(resets), period)       # 4 0.02001
```

2. **Compare with the formula.**
   $$\begin{aligned} T &= \frac{CV_{th}}{I} \\ &= \frac{(100\ \text{nF})(2.0\ \text{V})}{10\ \mu\text{A}} \\ &= 20\ \text{ms} \end{aligned}$$
   and the simulation gives 20.01 ms.
3. **Explain the extra step.** The simulation takes 2001 steps per cycle instead of 2000, because two thousand additions of 0.001 land just short of 2.0.
4. **Judge the error.** It is one time step, which is the most a stepped simulation can be trusted to resolve an event's time anyway.

**Answer:** the simulated period is 20.01 ms, one 10 µs step longer than the 20 ms the formula gives.
:::
:::

::: check
kind: python
given: Vs = 3.3 | 5 | 12; Vf = 1.8 | 2.0 | 3.1; I = 5 | 10 | 20

## Write `led(Vs, Vf, I_max)` returning `(R, rating)`: the smallest E12 resistor (from the starter's `values`) that keeps the current at or below `I_max` amps, and the smallest of 0.125, 0.25, 0.5 and 1 W that's at least twice its dissipation. Then set `R, rating = led(Vs, Vf, I / 1000)` for `Vs` = {Vs} V, `Vf` = {Vf} V and `I` = {I} mA.

```python starter
E12 = [1.0, 1.2, 1.5, 1.8, 2.2, 2.7, 3.3, 3.9, 4.7, 5.6, 6.8, 8.2]
values = [m * 10**d for d in range(7) for m in E12]

def led(Vs, Vf, I_max):
    R = (Vs - Vf) / I_max
    return R, None

R, rating = led(Vs, Vf, I / 1000)
print(R, rating)
```

```python solution
E12 = [1.0, 1.2, 1.5, 1.8, 2.2, 2.7, 3.3, 3.9, 4.7, 5.6, 6.8, 8.2]
values = [m * 10**d for d in range(7) for m in E12]

def led(Vs, Vf, I_max):
    ideal = (Vs - Vf) / I_max
    R = min(v for v in values if v >= ideal - 1e-9)
    P = (Vs - Vf)**2 / R
    rating = min(r for r in [0.125, 0.25, 0.5, 1] if r >= 2 * P)
    return R, rating

R, rating = led(Vs, Vf, I / 1000)
print(R, rating)
```

```python tests
E = [1.0, 1.2, 1.5, 1.8, 2.2, 2.7, 3.3, 3.9, 4.7, 5.6, 6.8, 8.2]
vals = sorted(m * 10**d for d in range(7) for m in E)
ideal = (Vs - Vf) / (I / 1000)
wR = min(v for v in vals if v >= ideal - 1e-9)
wP = (Vs - Vf)**2 / wR
wr = min(r for r in [0.125, 0.25, 0.5, 1] if r >= 2 * wP)
assert abs(R - wR) < 1e-6, f"R should be {wR:g} Ω, the smallest E12 value at or above {ideal:.4g} Ω."
assert (Vs - Vf) / R <= I / 1000 + 1e-12, "The current must not exceed I_max."
assert rating == wr, f"The resistor dissipates {wP * 1000:.1f} mW, so the rating should be {wr} W."
```

::: right
Right. Rounding the resistor up keeps the current under the limit, and the rating comes from the resistor actually chosen, not the ideal one.
:::
:::

::: check
kind: python
given: lo = 19 | 20; band = 1 | 2

## The starter makes `temps`, a day of room temperatures, one per minute. A thermostat turns the heater on when the temperature is below `lo` = {lo} °C and off when it's above `lo + band` ({band} °C higher), and otherwise leaves it as it was. Starting with the heater off, set `on` to a list of the heater's state each minute, `switches` to how many times it changed, and `duty` to the fraction of minutes it was on.

```python starter
import math
temps = [20.5 + 2.5 * math.sin(2 * math.pi * m / 1440) + 0.8 * math.sin(2 * math.pi * m / 37) for m in range(1440)]
on = [t < lo for t in temps]
switches = 0
duty = sum(on) / len(on)
print(switches, duty)
```

```python solution
import math
temps = [20.5 + 2.5 * math.sin(2 * math.pi * m / 1440) + 0.8 * math.sin(2 * math.pi * m / 37) for m in range(1440)]
state = False
on = []
switches = 0
for t in temps:
    new = state
    if t < lo:
        new = True
    elif t > lo + band:
        new = False
    if new != state:
        switches += 1
    state = new
    on.append(state)
duty = sum(on) / len(on)
print(switches, duty)
```

```python tests
import math
T = [20.5 + 2.5 * math.sin(2 * math.pi * m / 1440) + 0.8 * math.sin(2 * math.pi * m / 37) for m in range(1440)]
s, w, n = False, [], 0
for t in T:
    nw = True if t < lo else (False if t > lo + band else s)
    n += nw != s
    s = nw
    w.append(s)
assert on == w, "Keep the heater's state between minutes: below lo it turns on, above lo + band it turns off, in between it stays as it was."
assert switches == n, f"The heater should change state {n} times."
assert abs(duty - sum(w) / len(w)) < 1e-12, "duty is the fraction of minutes on."
```

::: right
Right. The state has to live outside the loop, because inside the band the decision depends on what the heater was already doing. A wider band means fewer switches, which is the whole point of hysteresis.
:::
:::

::: check
kind: python
given: Ic = 5 | 10 | 20; C = 47 | 100 | 220; Vth = 1 | 2 | 3

## A current source of `Ic` = {Ic} µA charges `C` = {C} nF until the voltage reaches `Vth` = {Vth} V, when it's discharged to zero at once. Simulate 0.5 s in steps of 10 µs. Set `n` to the number of discharges, `period` to the average spacing between them in seconds, and `ideal` to $CV_{th}/I$.

```python starter
dt = 10e-6
v = 0.0
n = 0
period = 0
ideal = 0
print(n, period, ideal)
```

```python solution
dt = 10e-6
Ia, Cf = Ic * 1e-6, C * 1e-9
v = 0.0
resets = []
for k in range(50000):
    v += Ia * dt / Cf
    if v >= Vth:
        v = 0.0
        resets.append(k)
n = len(resets)
period = (resets[-1] - resets[0]) / (n - 1) * dt
ideal = Cf * Vth / Ia
print(n, period, ideal)
```

```python tests
dt = 10e-6
a, c = Ic * 1e-6, C * 1e-9
w, rs = 0.0, []
for k in range(50000):
    w += a * dt / c
    if w >= Vth:
        w = 0.0
        rs.append(k)
assert n == len(rs), f"There should be {len(rs)} discharges in 0.5 s. Did you convert µA and nF?"
assert abs(period - (rs[-1] - rs[0]) / (len(rs) - 1) * dt) < 1e-12, "period is the average spacing between discharges, in seconds."
assert abs(ideal - c * Vth / a) < 1e-15 and abs(period - ideal) <= dt * 1.001, "ideal is C*Vth/I, and the simulation should agree with it to within a step."
```

::: right
Right. The simulated period agrees with $CV_{th}/I$ to within one time step, as close as a stepped simulation can time an event.
:::
:::

::: check
kind: python
given: fc = 100 | 1000 | 15900; g = 0.5 | 0.1 | 0.01

## Write `bisect(f, a, b, tol=1e-9)`, which halves `[a, b]` until it's narrower than `tol` times `b` and returns its midpoint (assume `f(a)` and `f(b)` have opposite signs). Use it with a `lambda` to set `f` to the frequency, between 1 Hz and 100 MHz, where an RC low-pass with corner `fc` = {fc} Hz has gain `g` = {g}: the gain is $1/\sqrt{1 + (f/f_c)^2}$.

```python starter
import math
def bisect(f, a, b, tol=1e-9):
    return (a + b) / 2

f = bisect(lambda x: 1 / math.sqrt(1 + (x / fc)**2), 1, 1e8)
print(f)
```

```python solution
import math
def bisect(f, a, b, tol=1e-9):
    fa = f(a)
    while b - a > tol * b:
        m = (a + b) / 2
        if (f(m) > 0) == (fa > 0):
            a, fa = m, f(m)
        else:
            b = m
    return (a + b) / 2

f = bisect(lambda x: 1 / math.sqrt(1 + (x / fc)**2) - g, 1, 1e8)
print(f)
```

```python tests
import math
exact = fc * math.sqrt(1 / g**2 - 1)
assert abs(f - exact) < 1e-6 * exact, f"The gain falls to {g} at {exact:.6g} Hz. Search for the zero of gain - g."
assert abs(bisect(lambda x: x * x - 2, 0, 2) - math.sqrt(2)) < 1e-8, "bisect should work for any function, such as x*x - 2 on [0, 2]."
```

::: right
Right. Bisection finds zeros, so the `lambda` subtracts the target gain. The answer has a formula, $f_c\sqrt{1/g^2 - 1}$, which is how you know the search works before using it on a filter whose gain has no formula.
:::
:::

::: check
kind: python
given: a = 10 | 100; b = 1000 | 100000; n = 5 | 7 | 11

## Write `sweep(start, stop, n=10, log=False)` returning a list of `n` values from `start` to `stop` inclusive: evenly spaced, or with equal ratios between neighbors when `log=True`. Then set `lin = sweep(a, b, n)` and `geo = sweep(a, b, n, log=True)` for `a` = {a}, `b` = {b} and `n` = {n}.

```python starter
def sweep(start, stop, n=10, log=False):
    step = (stop - start) / n
    return [start + k * step for k in range(n)]

lin = sweep(a, b, n)
geo = sweep(a, b, n, log=True)
print(lin, geo)
```

```python solution
def sweep(start, stop, n=10, log=False):
    if log:
        r = (stop / start) ** (1 / (n - 1))
        return [start * r**k for k in range(n)]
    step = (stop - start) / (n - 1)
    return [start + k * step for k in range(n)]

lin = sweep(a, b, n)
geo = sweep(a, b, n, log=True)
print(lin, geo)
```

```python tests
assert len(lin) == n and len(geo) == n, f"Both sweeps should have {n} points."
assert abs(lin[0] - a) < 1e-9 and abs(lin[-1] - b) < 1e-9 * b and abs(geo[-1] - b) < 1e-9 * b, "Both should start at start and end at stop: n points make n - 1 steps."
assert all(abs((lin[i + 1] - lin[i]) - (b - a) / (n - 1)) < 1e-9 * b for i in range(n - 1)), "The linear sweep has equal steps."
r = (b / a) ** (1 / (n - 1))
assert all(abs(geo[i + 1] / geo[i] - r) < 1e-9 for i in range(n - 1)), "The log sweep has equal ratios between neighbors."
assert len(sweep(1, 10)) == 10, "n should default to 10."
```

::: right
Right. $n$ points make $n - 1$ steps, the off-by-one that the starter gets wrong. A log sweep spaces frequencies the way a Bode plot shows them: equal ratios, so every decade gets the same number of points.
:::
:::

::: check
given: C = 47 | 100 | 220; I = 5 | 10 | 20; V = 1 | 2 | 3
answer: C*1e-9*V/(I*1e-6)
unit: s
tolerance: 1%

## A {I} µA current source charges {C} nF from 0 V. How long until the capacitor reaches {V} V?

::: right
Right. A constant current charges a capacitor at a constant rate, $dv/dt = I/C$, so $t = CV/I$ = {answer}.
:::

::: misses
- [C*V/I] That mixes nanofarads and microamps as if they were farads and amps. Convert both first.
- [C*1e-9*I*1e-6/V] That's upside down. The time is charge divided by current, and the charge is $CV$.
- [any] Not yet. The charge needed is $CV$; divide it by the current.
:::
:::

::: explain
## In the thermostat, why does the heater's state have to be kept outside the loop, while the temperature doesn't?

::: model
Each minute's temperature comes fresh from the list, but the heater's next state depends on its present one: inside the band the rule is "leave it as it was", which means nothing unless the loop remembers what it was. A variable set before the loop and updated at the end of each pass carries that memory from one minute to the next. Anything that only depends on the current input can be computed inside the loop; anything with memory, like a heater, a capacitor's voltage or a counter, has to live outside it.
:::
:::
