---
title: "Project: Monte Carlo tolerance analysis of a filter"
heading: Will ten thousand of these filters meet spec?
eyebrow: A4 · Project 2 · Tolerance analysis
xp: 60
---

::: hook
You've designed an active low-pass filter for a sensor: a Sallen-Key stage with two resistors and two capacitors, set for a 1.07 kHz corner and a Q of 0.74. On paper it's perfect. On a production line, every resistor is off by up to 1% and every capacitor by up to 5 or 10%, all at random. The customer's spec says the corner must be within ±5% and the Q within ±10%. In this project you'll find out what fraction of boards will pass, which part is to blame for the failures, and what one change would fix it.
:::

::: predict
## The corner frequency goes as $1/\sqrt{R_1R_2C_1C_2}$. If one capacitor is 10% high and everything else is exact, how far does the corner move?

- [ ] 10% low
- [x] About 5% low
- [ ] About 2.5% low
- [ ] 10% high

::: reveal
About 5% low: $1/\sqrt{1.1} = 0.953$. A square root halves the effect of each part's error on the corner. With four parts under the square root, their random errors partly cancel, which is exactly what the Monte Carlo will measure.
:::
:::

::: nameit
## The circuit and the plan

A unity-gain Sallen-Key low-pass has $R_1$ and $R_2$ in series from the input to the op amp's + input, $C_2$ from the + input to ground, and $C_1$ from the junction of the resistors back to the output. Its response is

$$H(s) = \frac{1}{1 + sC_2(R_1 + R_2) + s^2R_1R_2C_1C_2}$$

which is a second-order low-pass with

$$f_0 = \frac{1}{2\pi\sqrt{R_1R_2C_1C_2}} \qquad Q = \frac{\sqrt{R_1R_2C_1C_2}}{C_2(R_1 + R_2)}$$

C6 shows where this comes from. The design: $R_1 = R_2 = 10$ kΩ (±1%), $C_1 = 22$ nF (±5%) and $C_2 = 10$ nF (±10%). Model every tolerance as uniform.

**The plan:**
1. Write a function for $f_0$ and $Q$ and check the nominal design.
2. Simulate 50,000 boards and find the yield against the spec.
3. Find which part's tolerance hurts the most.
4. Plot the distribution of $f_0$ against the spec limits.

Use `rng = np.random.default_rng(0)` and draw the parts in the order R1, R2, C1, C2, so your numbers match the checks.
:::

::: check
kind: python

## Write `sk(R1, R2, C1, C2)` returning `(f0, Q)`, and set `f0_nom, Q_nom` for the nominal design.

```python starter
import numpy as np

def sk(R1, R2, C1, C2):
    return 0, 0

f0_nom, Q_nom = sk(10e3, 10e3, 22e-9, 10e-9)
print(f0_nom, Q_nom)
```

```python solution
import numpy as np

def sk(R1, R2, C1, C2):
    root = np.sqrt(R1 * R2 * C1 * C2)
    return 1 / (2 * np.pi * root), root / (C2 * (R1 + R2))

f0_nom, Q_nom = sk(10e3, 10e3, 22e-9, 10e-9)
print(f0_nom, Q_nom)
```

```python tests
import numpy as np
assert abs(f0_nom - 1 / (2 * np.pi * np.sqrt(1e8 * 2.2e-16))) < 1e-6, "f0 = 1/(2π√(R1R2C1C2))."
assert abs(Q_nom - np.sqrt(2.2) / 2) < 1e-12, "With R1 = R2, Q = √(C1/C2)/2 = 0.742. Check Q = √(R1R2C1C2)/(C2(R1 + R2))."
f, q = sk(np.array([1e3, 2e3]), 1e3, 1e-6, 1e-6)
assert np.shape(f) == (2,), "sk should work on arrays too, using np.sqrt."
```

::: right
Right: 1.073 kHz and a Q of 0.742, close to the 0.707 of a Butterworth filter.
:::
:::

::: check
kind: python

## Simulate 50,000 boards (uniform tolerances, `default_rng(0)`, parts drawn in the order R1, R2, C1, C2). Set `f0` and `Q` to the arrays of results, and `yld` to the fraction with $f_0$ within ±5% and $Q$ within ±10% of nominal.

```python starter
import numpy as np

def sk(R1, R2, C1, C2):
    root = np.sqrt(R1 * R2 * C1 * C2)
    return 1 / (2 * np.pi * root), root / (C2 * (R1 + R2))

f0_nom, Q_nom = sk(10e3, 10e3, 22e-9, 10e-9)
N = 50000
f0 = Q = None
yld = 0
print(yld)
```

```python solution
import numpy as np

def sk(R1, R2, C1, C2):
    root = np.sqrt(R1 * R2 * C1 * C2)
    return 1 / (2 * np.pi * root), root / (C2 * (R1 + R2))

f0_nom, Q_nom = sk(10e3, 10e3, 22e-9, 10e-9)
N = 50000
rng = np.random.default_rng(0)
R1 = 10e3 * rng.uniform(0.99, 1.01, N)
R2 = 10e3 * rng.uniform(0.99, 1.01, N)
C1 = 22e-9 * rng.uniform(0.95, 1.05, N)
C2 = 10e-9 * rng.uniform(0.90, 1.10, N)
f0, Q = sk(R1, R2, C1, C2)
ok = (np.abs(f0 / f0_nom - 1) <= 0.05) & (np.abs(Q / Q_nom - 1) <= 0.10)
yld = ok.mean()
print(yld)
```

```python tests
import numpy as np
rng = np.random.default_rng(0)
N = 50000
R1 = 10e3 * rng.uniform(0.99, 1.01, N); R2 = 10e3 * rng.uniform(0.99, 1.01, N)
C1 = 22e-9 * rng.uniform(0.95, 1.05, N); C2 = 10e-9 * rng.uniform(0.90, 1.10, N)
root = np.sqrt(R1 * R2 * C1 * C2)
ff, qq = 1 / (2 * np.pi * root), root / (C2 * (R1 + R2))
assert f0 is not None and np.allclose(f0, ff) and np.allclose(Q, qq), "Draw R1, R2, C1, C2 in that order from default_rng(0), each uniform over its tolerance band."
fn, qn = 1 / (2 * np.pi * np.sqrt(1e8 * 2.2e-16)), np.sqrt(2.2) / 2
assert abs(yld - np.mean((np.abs(ff / fn - 1) <= 0.05) & (np.abs(qq / qn - 1) <= 0.10))) < 1e-15, "A board passes only if both f0 and Q are within spec: combine the two masks with &."
```

::: right
Right. Most boards pass, but not all: the yield is the number that goes into the cost of the product.
:::
:::

::: check
kind: python

## Find which part matters most. For each of the four parts in turn, simulate 50,000 boards where only that part varies over its tolerance (the others exact; `default_rng(1)`, one fresh draw per part in the order R1, R2, C1, C2). Set `spread` to a dictionary from part name to the standard deviation of $f_0/f_{0,\text{nom}}$, and `worst` to the name with the largest.

```python starter
import numpy as np

def sk(R1, R2, C1, C2):
    root = np.sqrt(R1 * R2 * C1 * C2)
    return 1 / (2 * np.pi * root), root / (C2 * (R1 + R2))

f0_nom, Q_nom = sk(10e3, 10e3, 22e-9, 10e-9)
spread = {}
worst = None
print(spread, worst)
```

```python solution
import numpy as np

def sk(R1, R2, C1, C2):
    root = np.sqrt(R1 * R2 * C1 * C2)
    return 1 / (2 * np.pi * root), root / (C2 * (R1 + R2))

f0_nom, Q_nom = sk(10e3, 10e3, 22e-9, 10e-9)
rng = np.random.default_rng(1)
N = 50000
nominal = {"R1": 10e3, "R2": 10e3, "C1": 22e-9, "C2": 10e-9}
tol = {"R1": 0.01, "R2": 0.01, "C1": 0.05, "C2": 0.10}
spread = {}
for name in ["R1", "R2", "C1", "C2"]:
    parts = dict(nominal)
    parts[name] = nominal[name] * rng.uniform(1 - tol[name], 1 + tol[name], N)
    f, q = sk(parts["R1"], parts["R2"], parts["C1"], parts["C2"])
    spread[name] = (f / f0_nom).std()
worst = max(spread, key=spread.get)
print(spread, worst)
```

```python tests
assert set(spread) == {"R1", "R2", "C1", "C2"}, "spread should have an entry for each part."
assert worst == "C2", "The part with the widest tolerance dominates: C2, at ±10%."
assert abs(spread["C2"] / spread["C1"] - 2) < 0.1, "Each part's effect on f0 is half its own relative spread, so C2's should be about twice C1's."
```

::: right
Right. C2's ±10% tolerance drives most of the spread. Each part's relative error reaches $f_0$ halved, through the square root.
:::
:::

::: check
kind: python

## Replace C2 with a ±2% part and re-run the full simulation from the second lab (`default_rng(0)`, same order, 50,000 boards). Set `yld2` to the new yield. Then plot a histogram of $f_0$ (60 bins) with dashed vertical lines at the ±5% spec limits, and label the axes.

```python starter
import numpy as np
import matplotlib.pyplot as plt

def sk(R1, R2, C1, C2):
    root = np.sqrt(R1 * R2 * C1 * C2)
    return 1 / (2 * np.pi * root), root / (C2 * (R1 + R2))

f0_nom, Q_nom = sk(10e3, 10e3, 22e-9, 10e-9)
yld2 = 0
```

```python solution
import numpy as np
import matplotlib.pyplot as plt

def sk(R1, R2, C1, C2):
    root = np.sqrt(R1 * R2 * C1 * C2)
    return 1 / (2 * np.pi * root), root / (C2 * (R1 + R2))

f0_nom, Q_nom = sk(10e3, 10e3, 22e-9, 10e-9)
N = 50000
rng = np.random.default_rng(0)
R1 = 10e3 * rng.uniform(0.99, 1.01, N)
R2 = 10e3 * rng.uniform(0.99, 1.01, N)
C1 = 22e-9 * rng.uniform(0.95, 1.05, N)
C2 = 10e-9 * rng.uniform(0.98, 1.02, N)
f0, Q = sk(R1, R2, C1, C2)
yld2 = np.mean((np.abs(f0 / f0_nom - 1) <= 0.05) & (np.abs(Q / Q_nom - 1) <= 0.10))
plt.hist(f0, bins=60)
plt.axvline(0.95 * f0_nom, linestyle="--")
plt.axvline(1.05 * f0_nom, linestyle="--")
plt.xlabel("f0 (Hz)")
plt.ylabel("boards")
```

```python tests
import numpy as np
import matplotlib.pyplot as plt
rng = np.random.default_rng(0)
N = 50000
R1 = 10e3 * rng.uniform(0.99, 1.01, N); R2 = 10e3 * rng.uniform(0.99, 1.01, N)
C1 = 22e-9 * rng.uniform(0.95, 1.05, N); C2 = 10e-9 * rng.uniform(0.98, 1.02, N)
root = np.sqrt(R1 * R2 * C1 * C2)
ff, qq = 1 / (2 * np.pi * root), root / (C2 * (R1 + R2))
fn, qn = 1 / (2 * np.pi * np.sqrt(1e8 * 2.2e-16)), np.sqrt(2.2) / 2
assert abs(yld2 - np.mean((np.abs(ff / fn - 1) <= 0.05) & (np.abs(qq / qn - 1) <= 0.10))) < 1e-15, "Re-run the simulation with C2 uniform over ±2%."
ax = plt.gca()
assert len(ax.patches) >= 50, "Draw a histogram of f0 with plt.hist(f0, bins=60)."
xs = sorted(float(l.get_xdata()[0]) for l in ax.get_lines() if len(l.get_xdata()) == 2)
assert len(xs) >= 2 and abs(xs[0] - 0.95 * fn) < 1e-6 * fn and abs(xs[-1] - 1.05 * fn) < 1e-6 * fn, "Mark the spec limits at 0.95·f0 and 1.05·f0 with plt.axvline."
assert ax.get_xlabel() and ax.get_ylabel(), "Label both axes."
```

::: right
Right. A tighter C2 costs a little more but moves the yield close to 100%: a decision the Monte Carlo makes easy to price.
:::
:::

::: explain
## Using your results, explain to a manager why the filter failed spec on some boards and what the cheapest fix is.

::: model
The filter's corner frequency depends on all four parts, but each part's error reaches the corner halved, through a square root, and the random errors partly cancel. The resistors are 1% parts, so they barely matter. The two capacitors dominate, and C2, at ±10%, causes about twice the spread of C1. Replacing just C2 with a 2% part brings nearly every board within spec, so that one part change is the cheapest fix; tightening the resistors would cost money and change almost nothing.
:::
:::

::: practice

::: check
kind: python
given: t = 1 | 2 | 5

## A part's relative error is uniform over ±`t` = {t}%. Set `sd` to its standard deviation, as a fraction ($\text{half-width}/\sqrt{3}$), and `sd_f0` to the resulting spread of a corner that depends on it through a square root.

```python starter
sd = sd_f0 = 0
print(sd, sd_f0)
```

```python solution
sd = (t / 100) / 3 ** 0.5
sd_f0 = sd / 2
print(sd, sd_f0)
```

```python tests
assert abs(sd - t / 100 / 3**0.5) < 1e-15, "A uniform distribution of half-width a has standard deviation a/√3."
assert abs(sd_f0 - sd / 2) < 1e-15, "Through a square root, relative errors are halved."
```
:::

::: check
kind: python
given: c1 = 10 | 22 | 47; c2 = 10 | 4.7

## For a unity-gain Sallen-Key with equal resistors, set `Q` = $\sqrt{C_1/C_2}/2$ for `C1` = {c1} nF and `C2` = {c2} nF.

```python starter
Q = 0
print(Q)
```

```python solution
Q = (c1 / c2) ** 0.5 / 2
print(Q)
```

```python tests
assert abs(Q - (c1 / c2) ** 0.5 / 2) < 1e-12, "With R1 = R2, Q = √(C1/C2)/2."
```
:::
:::
