---
title: Random numbers and Monte Carlo
heading: Build ten thousand boards before you build one
eyebrow: A4 · Lesson 49 · Random numbers and Monte Carlo
xp: 40
---

::: hook
A filter's corner depends on a resistor and a capacitor, each a little off from its marked value in a random way. The worst case (both off in the bad direction) is easy to compute and rarely happens. What a manufacturer needs to know is how often a board will be out of spec. Simulate ten thousand boards, each with its own randomly drawn parts, and count. That's the Monte Carlo method, and with NumPy it's a few lines.
:::

::: predict
## A Monte Carlo yield estimate from 1000 simulated boards is 95%. Roughly how uncertain is that estimate?

- [ ] ±5%
- [x] ±0.7%
- [ ] ±0.07%
- [ ] It's exact, since the parts were simulated

::: reveal
About ±0.7%. Each board passes or fails, so the estimate's standard error is $\sqrt{p(1 - p)/N} = \sqrt{0.95 \times 0.05/1000} = 0.69\%$. Monte Carlo results are themselves random, with error shrinking as $1/\sqrt{N}$: four times the boards for half the uncertainty.
:::
:::

::: nameit
## Random numbers in NumPy

```
rng = np.random.default_rng(42)        # a seeded generator
rng.uniform(0.95, 1.05, size=10000)    # flat between two limits
rng.normal(1.0, 0.0167, size=10000)    # bell-shaped: mean, standard deviation
```

Always use a seeded generator for anything you'll check or report, so it can be repeated exactly.

## Modeling tolerances

A part marked ±5% can be modeled two ways:
- **uniform** across the band, a cautious choice when you know nothing else;
- **normal** with the band at $\pm 3\sigma$ (so $\sigma$ = tolerance/3), closer to what production lines often deliver.

Which you choose changes the tails of the result, which is where yield is decided, so say which one you used.

## The method

1. Draw every uncertain input as an array of $N$ samples.
2. Compute the output for all $N$ at once, with array arithmetic.
3. Summarize: the mean and standard deviation, the fraction within spec (the **yield**), percentiles with `np.percentile`.

```
N = 100_000
R = 10e3 * rng.normal(1, 0.05 / 3, N)
C = 10e-9 * rng.normal(1, 0.10 / 3, N)
fc = 1 / (2 * np.pi * R * C)
yield_ = np.mean(np.abs(fc / 1591.5 - 1) < 0.05)
```

## Accuracy

The standard error of a Monte Carlo mean is $s/\sqrt{N}$, and of a yield $\sqrt{p(1 - p)/N}$. Run with enough samples that this is small compared with the decision you're making. Rare failures (one in a million) need special techniques, since plain sampling would need hundreds of millions of draws to see a few.

## Monte Carlo against worst case

Worst-case analysis gives guaranteed bounds, but the bounds are usually far outside where real boards land. Monte Carlo gives the realistic spread but no guarantee. Engineers use worst case for safety-critical limits and Monte Carlo for cost and yield decisions.
:::

::: example
## A divider uses two 10 kΩ ±1% resistors, modeled as uniform. Compare the Monte Carlo spread of the ratio with the worst case.

::: solution
1. **Simulate 100,000 boards.** Draw each resistor uniformly within ±1% and compute the ratio.

```
import numpy as np
rng = np.random.default_rng(1)
N = 100_000
top = 10e3 * rng.uniform(0.99, 1.01, N)
bot = 10e3 * rng.uniform(0.99, 1.01, N)
r = bot / (top + bot)
print(r.std(), r.min(), r.max())     # about 0.00204, 0.4950, 0.5050
```

2. **The worst case.**
   $$\begin{aligned} r_{max} &= \frac{10.1}{9.9 + 10.1} \\ &= 0.505 \end{aligned}$$
   which is ±1%.
3. **The Monte Carlo spread.** Out of 100,000 simulated boards a few come close to the worst case, but the standard deviation is only 0.4% of the ratio and about 95% of boards are within ±0.8%.
4. **The shape.** The ratio's distribution is nearly triangular, peaked at 0.5, because to first order it depends on the difference of two flat errors.

**Answer:** the worst case is ±1%, but the Monte Carlo standard deviation is only 0.4%, and about 95% of boards fall within ±0.8%.
:::
:::

::: example
## Estimate $\pi$ by throwing random points at a square, and watch the error shrink.

::: solution
1. **Throw points at the square.** The fraction landing inside the unit circle is $\pi/4$, so four times it estimates $\pi$.

```
for N in (100, 10_000, 1_000_000):
    x, y = rng.uniform(-1, 1, (2, N))
    print(N, 4 * np.mean(x**2 + y**2 <= 1))
```

2. **Watch the error.** Each hundredfold increase in $N$ makes the typical error about ten times smaller, from a few percent to a few hundredths of a percent.

**Answer:** four times the fraction inside the circle estimates $\pi$, and the error falls about tenfold for each hundredfold increase in $N$.
:::
:::

::: check
kind: python
given: t = 1 | 5; s = 1 | 2 | 7

## With `rng = np.random.default_rng(s)` and `N = 100000`, draw top and bottom resistors of a 10 kΩ/10 kΩ divider as uniform within ±`t` = {t}%, top first. Set `r` to the array of ratios, `sd` to their standard deviation, and `frac` to the fraction within ±`t`/2 % of 0.5.

```python starter
import numpy as np
N = 100000
r = np.full(N, 0.5)
sd = frac = 0
print(sd, frac)
```

```python solution
import numpy as np
rng = np.random.default_rng(s)
N = 100000
top = 10e3 * rng.uniform(1 - t / 100, 1 + t / 100, N)
bot = 10e3 * rng.uniform(1 - t / 100, 1 + t / 100, N)
r = bot / (top + bot)
sd = r.std()
frac = np.mean(np.abs(r - 0.5) <= 0.5 * t / 200)
print(sd, frac)
```

```python tests
import numpy as np
rng = np.random.default_rng(s)
N = 100000
top = 10e3 * rng.uniform(1 - t / 100, 1 + t / 100, N)
bot = 10e3 * rng.uniform(1 - t / 100, 1 + t / 100, N)
rr = bot / (top + bot)
assert np.shape(r) == (N,) and np.allclose(r, rr), "Draw the top array first, then the bottom, both with rng.uniform, and compute bot / (top + bot)."
assert abs(sd - rr.std()) < 1e-15 and abs(frac - np.mean(np.abs(rr - 0.5) <= 0.5 * t / 200)) < 1e-15, "sd is r.std() and frac the mean of the in-spec mask."
```
:::

::: check
kind: python
given: tR = 1 | 5; tC = 5 | 10; spec = 3 | 5

## Model `R` = 10 kΩ ±`tR`% and `C` = 10 nF ±`tC`% as normal with $\sigma$ = tolerance/3. With `rng = np.random.default_rng(0)` and 200,000 draws (R first), set `fc` to the corner frequencies and `yld` to the fraction within ±`spec`% of the nominal corner.

```python starter
import numpy as np
fc = None
yld = 0
print(yld)
```

```python solution
import numpy as np
rng = np.random.default_rng(0)
N = 200000
R = 10e3 * rng.normal(1, tR / 300, N)
C = 10e-9 * rng.normal(1, tC / 300, N)
fc = 1 / (2 * np.pi * R * C)
f0 = 1 / (2 * np.pi * 10e3 * 10e-9)
yld = np.mean(np.abs(fc / f0 - 1) <= spec / 100)
print(yld)
```

```python tests
import numpy as np
rng = np.random.default_rng(0)
N = 200000
R = 10e3 * rng.normal(1, tR / 300, N)
C = 10e-9 * rng.normal(1, tC / 300, N)
f = 1 / (2 * np.pi * R * C)
f0 = 1 / (2 * np.pi * 10e3 * 10e-9)
assert fc is not None and np.allclose(fc, f), "Draw R then C with rng.normal(1, tolerance/300, N) scaled by the nominal values."
assert abs(yld - np.mean(np.abs(f / f0 - 1) <= spec / 100)) < 1e-15, "yld is the fraction with |fc/f0 − 1| ≤ spec/100."
```
:::

::: check
kind: python
given: p = 0.9 | 0.95 | 0.99; N = 1000 | 10000

## A Monte Carlo run of `N` = {N} boards finds a yield of `p` = {p}. Set `se` to the standard error of that estimate, and `N4` to how many boards would halve it.

```python starter
se = 0
N4 = N
print(se, N4)
```

```python solution
se = (p * (1 - p) / N) ** 0.5
N4 = 4 * N
print(se, N4)
```

```python tests
assert abs(se - (p * (1 - p) / N) ** 0.5) < 1e-15, "se is √(p(1 − p)/N)."
assert N4 == 4 * N, "The error falls as 1/√N, so halving it takes four times the boards."
```
:::

::: check
kind: python
given: s = 3 | 11 | 29

## Estimate $\pi$ with `rng = np.random.default_rng(s)` and 1,000,000 points drawn as `x, y = rng.uniform(-1, 1, (2, N))`. Set `pi_est` and `err` to its absolute error.

```python starter
import numpy as np
pi_est = 3
err = 0
print(pi_est, err)
```

```python solution
import numpy as np
rng = np.random.default_rng(s)
N = 1_000_000
x, y = rng.uniform(-1, 1, (2, N))
pi_est = 4 * np.mean(x**2 + y**2 <= 1)
err = abs(pi_est - np.pi)
print(pi_est, err)
```

```python tests
import numpy as np
rng = np.random.default_rng(s)
x, y = rng.uniform(-1, 1, (2, 1_000_000))
want = 4 * np.mean(x**2 + y**2 <= 1)
assert abs(pi_est - want) < 1e-15, "pi_est is 4 × the fraction of points inside the unit circle."
assert err < 0.01, "With a million points the error should be well under 0.01."
```
:::

::: check
kind: python
given: tR = 1 | 5; s = 1 | 7 | 42

## An LED driver has $I = (V_s - V_f)/R$. Model 100,000 boards with `rng = np.random.default_rng(s)`, drawing in this order: `Vs` normal with mean 5 V and $\sigma$ = 0.05 V, `Vf` normal with mean 2.0 V and $\sigma$ = 0.05 V, and `R` uniform within ±`tR` = {tR}% of 150 Ω. Set `I` to the currents, `yield_` to the fraction within 18 to 22 mA, and `worst` to the largest current.

```python starter
import numpy as np
rng = np.random.default_rng(s)
N = 100000
I = np.full(N, 0.02)
yield_ = 1.0
worst = I.max()
print(yield_, worst)
```

```python solution
import numpy as np
rng = np.random.default_rng(s)
N = 100000
Vs = rng.normal(5.0, 0.05, N)
Vf = rng.normal(2.0, 0.05, N)
R = rng.uniform(150 * (1 - tR / 100), 150 * (1 + tR / 100), N)
I = (Vs - Vf) / R
yield_ = np.mean((I >= 0.018) & (I <= 0.022))
worst = I.max()
print(yield_, worst)
```

```python tests
import numpy as np
r = np.random.default_rng(s)
N = 100000
a = r.normal(5.0, 0.05, N); b = r.normal(2.0, 0.05, N); c = r.uniform(150 * (1 - tR / 100), 150 * (1 + tR / 100), N)
II = (a - b) / c
assert np.shape(I) == (N,) and np.allclose(I, II), "Draw Vs, then Vf, then R, with N values each, and compute I = (Vs - Vf)/R."
assert abs(yield_ - np.mean((II >= 0.018) & (II <= 0.022))) < 1e-12, "yield_ is the fraction of I between 0.018 and 0.022 A."
assert abs(worst - II.max()) < 1e-15, "worst is I.max()."
```

::: right
Right. With ±{tR}% resistors the spread of $V_s - V_f$ and of $R$ combine; the simulation tells you what fraction of boards land in spec without assuming any formula for how the spreads add.
:::
:::

::: check
given: p = 0.9 | 0.95 | 0.99; se = 0.5 | 1 | 0.2
answer: p*(1 - p)/(se/100)^2
tolerance: 1%

## A Monte Carlo yield estimate near {p} has a standard error of $\sqrt{p(1-p)/N}$. How many simulated boards $N$ give a standard error of {se}%?

::: right
Right. Solving $\sqrt{p(1-p)/N} = \given{se}/100$ gives $N = p(1-p)/(\given{se}/100)^2$ = {answer} boards.
:::

::: misses
- [sqrt(p*(1 - p))/(se/100)] That forgets to square. The standard error goes as $1/\sqrt N$, so $N$ goes as one over its square.
- [p*(1 - p)/se^2] That uses {se} as a fraction instead of a percentage. Divide it by 100 first.
- [any] Not yet. Square both sides of $\sqrt{p(1-p)/N} = \given{se}/100$ and solve for $N$.
:::
:::

::: explain
## When would you trust a worst-case analysis over a Monte Carlo simulation, and when the reverse?

::: model
Worst case gives a guaranteed bound: if every part is within its tolerance, the output can't be outside it. That's what you want for safety limits or anything that must never fail. But it assumes every part sits at its extreme in the worst direction, which almost never happens, so it overstates the real spread. Monte Carlo shows how outputs are actually distributed and how often a design would fail, which is what matters for yield and cost decisions, but it's only as good as the tolerance distributions you assume and gives no guarantee about rare cases.
:::
:::

::: practice

::: check
kind: python
given: s = 1 | 2 | 4 | 8 | 11 | 42

## With `rng = np.random.default_rng(s)`, draw 10,000 values from a normal distribution with mean 5 and standard deviation 0.1. Set `p95` to the 95th percentile with `np.percentile`.

```python starter
import numpy as np
p95 = 5
print(p95)
```

```python solution
import numpy as np
rng = np.random.default_rng(s)
x = rng.normal(5, 0.1, 10000)
p95 = np.percentile(x, 95)
print(p95)
```

```python tests
import numpy as np
x = np.random.default_rng(s).normal(5, 0.1, 10000)
assert abs(p95 - np.percentile(x, 95)) < 1e-12, "Use np.percentile(x, 95)."
```
:::

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

## For two independent ±`t`% uniform resistors in series, set `worst` to the worst-case relative error of the total, in percent.

```python starter
worst = 2 * t
print(worst)
```

```python solution
worst = t
print(worst)
```

```python tests
assert abs(worst - t) < 1e-12, "For two equal resistors in series, the total is off by at most the same percentage as each: both at +t% gives +t%."
```
:::
:::
