---
title: "Lab: tolerance analysis in code"
heading: Sensitivities, worst cases and a thousand random boards
eyebrow: A5 · Lesson 23 · Lab: tolerance analysis in code
xp: 60
---

::: hook
A designer choosing between 1% and 5% resistors needs to know how far the circuit's output will wander. The sensitivity lesson gave two estimates: the worst case, where every part is at its limit in the harmful direction, and a root-sum-square estimate for random errors. In this lab you'll compute sensitivities numerically for any circuit formula, make both estimates, and then check them by building twenty thousand random boards in software.
:::

::: play
- A divider of $R_1$ = 10 kΩ over $R_2$ = 4.7 kΩ, loaded by $R_L$, has output fraction $H = \frac{R_2 \parallel R_L}{R_1 + R_2 \parallel R_L}$. The curves are the three parts' sensitivities against the load, in kΩ.
- Move the marked load lower. The load starts to matter: its sensitivity grows while that of $R_2$ shrinks.
- With a light load, $R_L$ barely matters even at 5% tolerance: its sensitivity is small.
:::

```sim plot
view: graph
x: RL = 1..100 log
y: S = -1..1
slider: RLs = 1..100 = 47
plot: -10/(10 + 4.7*RL/(4.7 + RL)) | samples: 300 | label: S of R1
plot: 10/(10 + 4.7*RL/(4.7 + RL))*RL/(4.7 + RL) | samples: 300 | color: ch2 | label: S of R2
plot: 10/(10 + 4.7*RL/(4.7 + RL))*4.7/(4.7 + RL) | samples: 300 | color: ch3 | label: S of RL
marker: RL = RLs | label: your load
readout: output fraction = (4.7*RLs/(4.7 + RLs))/(10 + 4.7*RLs/(4.7 + RLs)) | digits: 4
```

::: predict
## Three parts have sensitivities 0.7, 0.64 and 0.064, with tolerances 1%, 1% and 5%. Twenty thousand random boards are built with each part uniformly distributed within its tolerance. About how big is the spread (standard deviation) of the output?

- [ ] 1.7%, the worst case
- [ ] 1.0%, the root-sum-square of the tolerances
- [x] About 0.58%
- [ ] 0.064%

::: reveal
About 0.58%. A part spread uniformly over $\pm t$ has a standard deviation of $t/\sqrt3$, not $t$, so the root-sum-square of the tolerances, 1.0%, divided by $\sqrt3$ gives the expected spread, 0.58%. The worst case, 1.7%, is reached only when every part sits at its limit in the harmful direction at once, which almost never happens.
:::
:::

::: nameit
## Numerical sensitivity

For a formula $y = f(p_1, p_2, \ldots)$, the sensitivity to $p_i$ is $\frac{\partial\ln y}{\partial\ln p_i}$. Numerically: multiply $p_i$ by $1 + \delta$ and by $1 - \delta$, and divide the change in $\ln y$ by the change in $\ln p_i$. With $\delta = 10^{-6}$, that's accurate to about 10 digits.

## Two predictions

With tolerances $t_i$ (as fractions):
- **worst case:** $\sum_i |S_i|\,t_i$;
- **root-sum-square:** $\sqrt{\sum_i (S_it_i)^2}$. If each part is uniform over $\pm t_i$, its standard deviation is $t_i/\sqrt3$, so the output's standard deviation is the root-sum-square divided by $\sqrt3$.

## Monte Carlo

Draw each part's value at random within its tolerance, compute the output, and repeat many times. The spread of the results is the real answer for that model of the parts, including any nonlinearity the sensitivities miss. `random.seed` makes the run repeatable, and `random.uniform(-t, t)` draws one part's fractional error.
:::

::: example
## A divider has $R_1$ = 10 kΩ, $R_2$ = 4.7 kΩ and a 47 kΩ load. What are its sensitivities?

::: solution
1. **Combine $R_2$ and the load.**
   $$R_2 \parallel R_L = 4.27\ \text{k}\Omega$$
2. **Ratio.**
   $$\begin{aligned} H &= \frac{4.27}{14.27} \\ &= 0.299 \end{aligned}$$
3. **Sensitivities, found numerically.** They are $-0.701$ to $R_1$, $0.637$ to $R_2$ and $0.064$ to $R_L$.
4. **Check.** They sum to zero, as they must: scaling every resistor by the same factor leaves a ratio unchanged.

**Answer:** the sensitivities are $-0.701$ to $R_1$, $0.637$ to $R_2$ and $0.064$ to $R_L$.
:::
:::

::: example
## With tolerances of 1%, 1% and 5% on those parts, what are the worst-case and root-sum-square errors?

::: solution
1. **Worst case.** Add each sensitivity times its tolerance:
   $$\begin{aligned} &0.701 \times 1 + 0.637 \times 1 \\ &\quad + 0.064 \times 5 \\ &= 1.66\% \end{aligned}$$
2. **Root-sum-square.**
   $$\begin{aligned} &\sqrt{0.701^2 + 0.637^2 + 0.318^2} \\ &= 1.00\% \end{aligned}$$
3. **Why the load adds little.** The load's 5% tolerance adds little, because its sensitivity is small.

**Answer:** the worst-case error is 1.66% and the root-sum-square error is 1.00%.
:::
:::

::: check
given: s1 = 0.7 | 1; s2 = 0.5 | 0.64; s3 = 0.064 | 0.25; t3 = 2 | 5
answer: s1 + s2 + s3*t3
tolerance: 0.5%

## Three parts have sensitivities {s1}, {s2} and {s3}, with tolerances 1%, 1% and {t3}%. What is the worst-case error, in percent?

::: right
Right. $\sum|S_i|t_i$ = {answer}%.
:::

::: misses
- [sqrt(s1^2 + s2^2 + (s3*t3)^2)] That's the root-sum-square.
- [any] Not yet. Add each sensitivity times its tolerance.
:::
:::

::: check
given: r = 0.6 | 1 | 2.5
answer: r/sqrt(3)
tolerance: 0.5%

## The root-sum-square of the sensitivity-weighted tolerances is {r}%. If every part is uniform within its tolerance, what standard deviation do you expect for the output, in percent?

::: right
Right. A uniform spread over $\pm t$ has standard deviation $t/\sqrt3$: {answer}%.
:::

::: misses
- [r] That treats each tolerance as a standard deviation. A uniform spread's is smaller.
- [any] Not yet. Divide by $\sqrt3$.
:::
:::

::: check
kind: python

## Write `sens(f, p, i, rel=1e-6)` returning the sensitivity of `f(p)` to `p[i]`, from the change in $\ln f$ when `p[i]` is multiplied by $1 \pm$ `rel`. Test it on an RC corner, $f = 1/(2\pi RC)$ with `p = [R, C]`.

```python starter
import math

def sens(f, p, i, rel=1e-6):
    return 0

fc = lambda p: 1 / (2 * math.pi * p[0] * p[1])
print(sens(fc, [1e4, 1e-8], 0), sens(fc, [1e4, 1e-8], 1))
```

```python solution
import math

def sens(f, p, i, rel=1e-6):
    q = list(p)
    q[i] = p[i] * (1 + rel)
    up = f(q)
    q[i] = p[i] * (1 - rel)
    dn = f(q)
    return (math.log(up) - math.log(dn)) / (math.log(1 + rel) - math.log(1 - rel))

fc = lambda p: 1 / (2 * math.pi * p[0] * p[1])
print(sens(fc, [1e4, 1e-8], 0), sens(fc, [1e4, 1e-8], 1))
```

```python tests
import math
fc = lambda p: 1 / (2 * math.pi * p[0] * p[1])
assert abs(sens(fc, [1e4, 1e-8], 0) + 1) < 1e-8 and abs(sens(fc, [1e4, 1e-8], 1) + 1) < 1e-8, "An RC corner has sensitivity -1 to both parts."
f0 = lambda p: 1 / (2 * math.pi * math.sqrt(p[0] * p[1]))
assert abs(sens(f0, [1e-3, 1e-6], 0) + 0.5) < 1e-8, "A resonance has sensitivity -1/2 to L."
assert abs(sens(lambda p: p[0] ** 3 * p[1], [2.0, 5.0], 0) - 3) < 1e-8, "A cube gives a sensitivity of 3."
```

::: right
Right. Working in logarithms turns "percent per percent" into an ordinary slope.
:::
:::

::: check
kind: python
given: t3 = 2 | 5 | 10

## For the loaded divider in the starter, set `S` to the list of sensitivities to `R1`, `R2` and `RL` (use your `sens`), then `wc` and `rss` to the worst-case and root-sum-square errors as fractions, with tolerances of 1%, 1% and `t3` = {t3}% on the load.

```python starter
import math

def sens(f, p, i, rel=1e-6):
    q = list(p)
    q[i] = p[i] * (1 + rel)
    up = f(q)
    q[i] = p[i] * (1 - rel)
    dn = f(q)
    return (math.log(up) - math.log(dn)) / (math.log(1 + rel) - math.log(1 - rel))

def H(p):
    R1, R2, RL = p
    P = R2 * RL / (R2 + RL)
    return P / (R1 + P)

p = [10e3, 4.7e3, 47e3]
S = []
wc = rss = 0
print(S, wc, rss)
```

```python solution
import math

def sens(f, p, i, rel=1e-6):
    q = list(p)
    q[i] = p[i] * (1 + rel)
    up = f(q)
    q[i] = p[i] * (1 - rel)
    dn = f(q)
    return (math.log(up) - math.log(dn)) / (math.log(1 + rel) - math.log(1 - rel))

def H(p):
    R1, R2, RL = p
    P = R2 * RL / (R2 + RL)
    return P / (R1 + P)

p = [10e3, 4.7e3, 47e3]
S = [sens(H, p, i) for i in range(3)]
tol = [0.01, 0.01, t3 / 100]
wc = sum(abs(s) * t for s, t in zip(S, tol))
rss = math.sqrt(sum((s * t) ** 2 for s, t in zip(S, tol)))
print(S, wc, rss)
```

```python tests
import math
assert abs(S[0] + 0.70064) < 1e-4 and abs(S[1] - 0.63694) < 1e-4 and abs(S[2] - 0.063694) < 1e-5, f"The sensitivities are -0.701, 0.637 and 0.064; got {S}."
assert abs(sum(S)) < 1e-8, "Scaling every resistor together leaves a ratio unchanged, so the sensitivities sum to zero."
tol = [0.01, 0.01, t3 / 100]
assert abs(wc - sum(abs(s) * t for s, t in zip(S, tol))) < 1e-12 and wc > rss, "wc should add |S| times tolerance, and exceed rss."
```

::: right
Right. The sensitivities summing to zero is a free check that comes from the divider being a ratio.
:::
:::

::: check
kind: python
given: n = 5000 | 8000 | 10000 | 15000 | 20000

## Build `n` = {n} random boards with `random.seed(2)`: each part is its nominal value times $1 + $ `random.uniform(-t, t)` with tolerances 1%, 1% and 5%. Set `spread` to the standard deviation of the output's fractional error $H/H_0 - 1$, and `worst` to the largest absolute error seen.

```python starter
import math, random

def H(p):
    R1, R2, RL = p
    P = R2 * RL / (R2 + RL)
    return P / (R1 + P)

p = [10e3, 4.7e3, 47e3]
tol = [0.01, 0.01, 0.05]
spread = worst = 0
print(spread, worst)
```

```python solution
import math, random

def H(p):
    R1, R2, RL = p
    P = R2 * RL / (R2 + RL)
    return P / (R1 + P)

p = [10e3, 4.7e3, 47e3]
tol = [0.01, 0.01, 0.05]
random.seed(2)
h0 = H(p)
errs = []
for _ in range(n):
    q = [x * (1 + random.uniform(-t, t)) for x, t in zip(p, tol)]
    errs.append(H(q) / h0 - 1)
m = sum(errs) / len(errs)
spread = math.sqrt(sum((e - m) ** 2 for e in errs) / (len(errs) - 1))
worst = max(abs(e) for e in errs)
print(spread, worst)
```

```python tests
import math
assert abs(spread - 0.00999 / math.sqrt(3)) < 0.0003, f"The spread should match the root-sum-square over sqrt(3), 0.577%; got {spread:.5f}."
assert 0.012 < worst < 0.0167, f"The worst board should come close to, but not beyond, the 1.66% worst case; got {worst:.5f}."
```

::: right
Right. The simulation lands on the root-sum-square prediction, and even twenty thousand boards rarely reach the worst case.
:::
:::

::: check
kind: python

## Which part should get a tighter tolerance? For each part in turn, cut its tolerance to a tenth (1% to 0.1%, or 5% to 0.5%) and recompute the root-sum-square error. Set `best` to the index (0, 1 or 2) of the part whose tightening helps most, and `gain` to how much the root-sum-square falls, as a fraction.

```python starter
import math

S = [-0.70064, 0.63694, 0.063694]
tol = [0.01, 0.01, 0.05]
best = 0
gain = 0
print(best, gain)
```

```python solution
import math

S = [-0.70064, 0.63694, 0.063694]
tol = [0.01, 0.01, 0.05]
rss = lambda t: math.sqrt(sum((s * x) ** 2 for s, x in zip(S, t)))
base = rss(tol)
results = []
for i in range(3):
    t = list(tol)
    t[i] /= 10
    results.append(base - rss(t))
best = max(range(3), key=lambda i: results[i])
gain = results[best]
print(best, gain)
```

```python tests
import math
assert best == 0, f"R1 has the largest weighted error, so tightening it helps most; got {best}."
assert abs(gain - 0.0028345) < 2e-5, f"Tightening R1 cuts the root-sum-square from 1.00% to about 0.72%; got a fall of {gain:.5f}."
```

::: right
Right. Spending money on the part with the largest $|S_i|t_i$ buys the most accuracy; tightening the load's tolerance would hardly help.
:::
:::

::: explain
## A designer finds that the worst-case error of a circuit is 3%, but a Monte Carlo run of 10,000 boards never shows more than 1.4%. Which number should go in the specification?

::: model
It depends on what the specification promises. The worst case is a guarantee: it covers every combination of parts within their tolerances, including the rare one where all errors line up in the harmful direction. If every unit shipped must meet the spec, for example in a safety or calibration circuit, the worst case is the honest number, perhaps with margin for temperature and aging. The Monte Carlo result describes typical boards: with independent random errors, combinations near the worst case are so unlikely that 10,000 samples rarely see one. If the spec is statistical, such as 99.7% of units within a limit, the simulated distribution (about three standard deviations) is the right basis and the worst case would over-design the circuit. Either way, the simulation is only as good as its model of the parts: if part errors are correlated, for instance resistors from one reel all running high, the true spread is larger than the independent model predicts.
:::
:::

::: practice

::: check
given: s1 = 0.1..1; s2 = 0.1..1; t1 = 0.1..5; t2 = 0.1..5
answer: s1*t1 + s2*t2
tolerance: 0.5%

## Worst case: sensitivities {s1} and {s2}, tolerances {t1}% and {t2}%?

::: misses
- [any] $\sum|S_i|t_i$.
:::
:::

::: check
given: s1 = 0.1..1; s2 = 0.1..1; t1 = 0.1..5; t2 = 0.1..5
answer: sqrt((s1*t1)^2 + (s2*t2)^2)
tolerance: 0.5%

## Root-sum-square: sensitivities {s1} and {s2}, tolerances {t1}% and {t2}%?

::: misses
- [any] $\sqrt{\sum(S_it_i)^2}$.
:::
:::
:::
