---
title: Monte Carlo simulation
heading: Estimating chances by simulating them in NumPy
eyebrow: A11 · Lesson 31 · Monte Carlo simulation
xp: 50
---

::: hook
A voltage divider made of two 1% resistors should give 2.5 V. What fraction of production units land within ±0.5%? You could work out the distribution of the output by convolution, but with a nonlinear formula and several parts that quickly gets hard. Or you could build a hundred thousand dividers in software, measure them all, and count. That's Monte Carlo simulation: estimate a probability as a long-run frequency (lesson 1) with the computer doing the long run, and use the law of large numbers (lesson 29) to know how far to trust the answer.
:::

::: play
- Each draw builds one 10k/10k divider from 5 V, each resistor uniform within ±$t$%. The histogram is the output voltage.
- With two parts the shape is a triangle, not a Gaussian; the line is the exact triangle.
- The readouts compare the measured fraction within the spec with the triangle and with a Gaussian of the same spread. Which prediction does the simulation agree with?
:::
:::

```sim plot
view: random
x: v = 2.38..2.62 V
slider: t = 0.5..5 step 0.5 = 1 %
slider: spec = 0.1..3 step 0.1 = 0.5 %
sample: 5/(1 + (1 + t/100*(2*rand(1) - 1))/(1 + t/100*(2*rand(1) - 1))) | sd: S
trials: 50000
bins: 96
density: step(2.5*t/100 - abs(v - 2.5))*(2.5*t/100 - abs(v - 2.5))/(2.5*t/100)^2
measure: step(spec/100*2.5 - abs(v - 2.5)) | name: P
readout: within spec, measured = P | digits: 3
readout: within spec, triangle = step(t - spec)*(1 - (1 - spec/t)^2) + step(spec - t) | digits: 3
readout: within spec, Gaussian = 1 - 2*Q(spec/t*sqrt(6)) | digits: 3
readout: standard deviation, mV = 1000*S | digits: 3
```

::: predict
## A simulation runs 10,000 trials to estimate a probability near 0.5. About how precise is the estimate?

- [ ] Exact
- [ ] ±0.05
- [x] ±0.005
- [ ] ±0.0001

::: reveal
About ±0.005, one standard deviation: $\sqrt{\frac{0.5 \times 0.5}{10\,000}} = 0.005$. Monte Carlo error shrinks only as $\frac{1}{\sqrt n}$: a hundred times more trials buys one more digit. That's the main cost of the method, and the reason to compare against a formula whenever one exists.
:::
:::

::: nameit
## The method

1. Write the system as a function of its random inputs: resistor values, noise samples, arrival times.
2. Draw many independent sets of inputs from their distributions.
3. Compute the output for each set, and estimate what you need from the results: a fraction (yield, error rate), a mean, a spread, a histogram.
4. Attach an error bar. A fraction $\hat p$ from $n$ trials has standard deviation $\sqrt{\hat p(1 - \hat p)/n}$; a mean has $\frac{s}{\sqrt n}$.

The method doesn't care how complicated the function is, which is why circuit simulators offer Monte Carlo runs over part tolerances and why communication systems are checked by simulating millions of bits.

## In NumPy

```python
import numpy as np
rng = np.random.default_rng(1)        # a generator with a fixed seed
r = rng.uniform(-1, 1, 100_000)       # 100,000 uniform draws at once
z = rng.normal(0, 0.5, 100_000)       # Gaussian, mean 0, sd 0.5
bits = rng.integers(0, 2, 100_000)    # random 0s and 1s
p_hat = np.mean(np.abs(z) > 1)        # a fraction: the mean of a True/False array
```

- **Vectorize:** draw arrays and compute on whole arrays; a Python loop over a million trials is a hundred times slower.
- **Fix the seed** while developing, so a run can be repeated exactly and a bug isn't mistaken for noise. Change it to check the answer doesn't depend on it.
- **Check against a case you can solve.** A simulation that reproduces a known formula is far more believable in the cases you can't solve.

## Rare events

To estimate a probability $p$ to a relative error $r$, you need about $\frac{1}{r^2}$ occurrences, so about $\frac{1}{r^2p}$ trials. A bit error rate of $10^{-9}$ is out of reach by plain simulation; engineers use formulas, bias the simulation toward errors (importance sampling), or extrapolate from higher noise.
:::

::: example
## Simulating 100,000 of the 10k/10k dividers with ±1% resistors gives a mean of 2.49999 V and a standard deviation of 10.22 mV, with 74.9% within ±0.5% (±12.5 mV). How do these compare with the formulas?

::: solution
1. **Sensitivity.** Linearizing,
   $$\begin{aligned} \frac{\partial V}{\partial R_1} &= -\frac{5R_2}{(R_1 + R_2)^2} \\ &= -1.25 \times 10^{-4}\ \text{V}/\Omega \end{aligned}$$
2. **Spread of each resistor.**
   $$\begin{aligned} \sigma &= \frac{200}{\sqrt{12}} \\ &= 57.7\ \Omega \end{aligned}$$
3. **Spread of the output.**
   $$\begin{aligned} \sigma_V &= \sqrt2 \times 1.25 \times 10^{-4} \times 57.7 \\ &= 10.21\ \text{mV} \end{aligned}$$
   agreeing with the simulation to 0.2%.
4. **Fraction within spec.** The output error is close to the difference of two uniform errors, a triangle reaching ±25 mV, so
   $$\begin{aligned} P &= 1 - \left(1 - \frac{12.5}{25}\right)^2 \\ &= 0.75 \end{aligned}$$
5. **Compare with a Gaussian.** A Gaussian with the same spread would predict 78%: with only two parts, the central limit theorem hasn't taken hold yet, and the simulation catches it.

**Answer:** the formulas give 10.21 mV and 75% within spec, close to the simulation's 10.22 mV and 74.9%.
:::
:::

::: example
## A simulation of 200,000 bits at $A/\sigma = 2$ counts 4513 errors. What BER does it measure, and is it consistent with $Q(2)$?

::: solution
1. **Measured BER.**
   $$\begin{aligned} \hat p &= \frac{4513}{200\,000} \\ &= 0.0226 \end{aligned}$$
2. **Its standard deviation.**
   $$\sqrt{\frac{0.0226 \times 0.977}{200\,000}} = 0.00033$$
3. **Compare with $Q(2)$.** $Q(2) = 0.02275$ lies within one standard deviation, so the simulation agrees with the formula.

**Answer:** it measures a BER of 0.0226, with a standard deviation of 0.00033, consistent with $Q(2) = 0.02275$.
:::
:::

::: check
given: p = 0.5 | 0.1; e = 0.01 | 0.005
answer: p*(1 - p)/e^2
tolerance: 0.5%

## A simulation estimates a probability near {p}. How many trials give a standard deviation of {e}?

::: right
Right. $n = \frac{p(1 - p)}{\varepsilon^2}$ = {answer}.
:::

::: misses
- [p*(1 - p)/e] Square the target error.
- [any] Not yet. Solve $\sqrt{p(1 - p)/n} = \varepsilon$.
:::
:::

::: check
given: t = 1 | 2 | 5
answer: 1000*1.25*sqrt(2)*(2*t/100)/sqrt(12)
unit: mV
tolerance: 1%

## A 10k/10k divider runs from 5 V, and each resistor is uniform within ±{t}%. What is the standard deviation of the output, by linearization?

::: right
Right. Each resistor contributes $1.25$ V per unit of relative error times $\frac{2t}{\sqrt{12}}$; the two add in quadrature: {answer}.
:::

::: misses
- [1000*1.25*(2*t/100)/sqrt(12)] Two resistors contribute; include $\sqrt2$.
- [1000*1.25*sqrt(2)*(t/100)] The standard deviation of a uniform error of ±t is $\frac{2t}{\sqrt{12}}$, not $t$.
- [any] Not yet. $\partial V/\partial R$ times each resistor's $\sigma$, combined by root-sum-square.
:::
:::

::: check
given: n = 1000 | 5000; f = 0.95 | 0.98
answer: sqrt(f*(1 - f)/n)
tolerance: 0.5%

## A Monte Carlo run of {n} circuits finds a fraction {f} within spec. What is the standard deviation of that yield estimate?

::: right
Right. $\sqrt{\hat p(1 - \hat p)/n}$ = {answer}.
:::

::: misses
- [sqrt(f/n)] Use $\hat p(1 - \hat p)$.
- [any] Not yet. The spread of an estimated fraction.
:::
:::

::: check
kind: python

## Write `divider_mc(n, rng, tol)` returning an array of `n` output voltages of a 10 kΩ/10 kΩ divider from 5 V, each resistor drawn as `10e3 * (1 + tol * rng.uniform(-1, 1, n))`. The test checks the mean, the spread and the yield within ±0.5%.

```python starter
import numpy as np

def divider_mc(n, rng, tol=0.01):
    return np.full(n, 2.5)

v = divider_mc(100_000, np.random.default_rng(1))
print(v.mean(), v.std())
```

```python solution
import numpy as np

def divider_mc(n, rng, tol=0.01):
    r1 = 10e3 * (1 + tol * rng.uniform(-1, 1, n))
    r2 = 10e3 * (1 + tol * rng.uniform(-1, 1, n))
    return 5 * r2 / (r1 + r2)

v = divider_mc(100_000, np.random.default_rng(1))
print(v.mean(), v.std())
```

```python tests
import numpy as np
v = divider_mc(100_000, np.random.default_rng(7))
assert len(v) == 100_000, "Return one voltage per trial."
assert abs(v.mean() - 2.5) < 0.001, f"The mean should be very close to 2.5 V; got {v.mean():.4f}."
assert abs(v.std() - 0.010206) / 0.010206 < 0.03, f"The spread should be about 10.2 mV; got {1000 * v.std():.2f} mV."
y = np.mean(np.abs(v - 2.5) <= 0.0125)
assert abs(y - 0.75) < 0.01, f"About 75% should be within ±0.5%; got {100 * y:.1f}%."
```

::: right
Right. Try `tol=0.05`: the spread scales by 5 and the yield within ±0.5% falls to about 19%.
:::
:::

::: check
kind: python

## Write `ber_mc(r, n, rng)`: send `n` random bits as ±1, add Gaussian noise with standard deviation `1/r` (so $A/\sigma = r$), decide by the sign, and return the fraction of bits decided wrong. The test compares with $Q(r)$.

```python starter
import numpy as np

def ber_mc(r, n, rng):
    return 0.0

print(ber_mc(2, 200_000, np.random.default_rng(2)))
```

```python solution
import numpy as np

def ber_mc(r, n, rng):
    bits = rng.integers(0, 2, n)
    x = 2 * bits - 1.0
    y = x + rng.normal(0, 1 / r, n)
    return np.mean((y > 0) != (bits == 1))

print(ber_mc(2, 200_000, np.random.default_rng(2)))
```

```python tests
import numpy as np
from math import erfc, sqrt
for r, q in ((1, 0.5 * erfc(1 / sqrt(2))), (2, 0.5 * erfc(2 / sqrt(2)))):
    p = ber_mc(r, 400_000, np.random.default_rng(11))
    sd = sqrt(q * (1 - q) / 400_000)
    assert abs(p - q) < 4 * sd, f"At A/σ = {r} the error rate should be near Q({r}) = {q:.4f}; got {p:.4f}."
assert ber_mc(5, 10_000, np.random.default_rng(3)) < 0.001, "With A/σ = 5 errors should be very rare."
```

::: right
Right. Try $r = 4$: $Q(4) = 3.2 \times 10^{-5}$, so 200,000 bits show only about 6 errors, and the estimate jumps around from seed to seed.
:::
:::

::: explain
## Why does Monte Carlo error shrink only as $1/\sqrt n$, and what does that mean in practice?

::: model
Each trial is an independent draw, and the estimate is an average of $n$ of them. By the law of large numbers its standard deviation is $\sigma/\sqrt n$. So halving the error takes four times as many trials, and each extra digit of precision costs a hundred times more computing. In practice you choose $n$ from the precision you need, you always report the error bar with the estimate, and for very rare events you need a smarter method or a formula, because plain simulation would take far too long.
:::
:::

::: practice

::: check
given: k = 100 | 2500; n = 10000 | 100000
answer: k/n
tolerance: 0.5%

## A simulation of {n} trials sees {k} failures. What is the estimated failure probability?

::: misses
- [any] $k/n$.
:::
:::

::: check
given: f = 2..20 int
answer: f^2
tolerance: 0.5%

## By what factor must the number of trials grow to make the Monte Carlo error {f} times smaller?

::: misses
- [f] Error falls as $1/\sqrt n$.
- [any] $f^2$.
:::
:::

::: check
given: p = 1e-3 | 1e-4; r = 0.1 | 0.3
answer: 1/(r^2*p)
tolerance: 0.5%

## About how many trials does a simulation need to estimate a probability near {p} with relative error {r}?

::: misses
- [1/p] That sees about one event.
- [any] About $1/r^2$ events.
:::
:::
:::
