---
title: "Lab: probability by simulation"
heading: Checking probability rules by running the experiment a million times
eyebrow: A11 · Lesson 7 · Lab: probability by simulation
xp: 60
---

::: hook
Lessons 1 to 6 computed probabilities with rules: complements, counting, conditioning, Bayes, independence. Each rule can be checked by brute force: simulate the random experiment many times and count. In this lab you'll do that for the birthday problem, a fault test where Bayes's rule surprises, a voting system's reliability, packet losses and bit errors. When the simulation and the formula agree, you can trust both; when they don't, one of them has a mistake.
:::

::: play
- A simulated estimate of a probability $p$ from $N$ trials has a standard deviation of $\sqrt{p(1 - p)/N}$.
- The curve shows that spread against $N$ for the $p$ you choose. The readout gives the trials needed for a 1% relative error.
- Small probabilities need many trials: the relative error is about $\frac{1}{\sqrt{pN}}$.
:::

```sim plot
view: graph
x: N = 100..1000000
y: spread = 0.00001..0.1 log
slider: p = 0.001..0.5 step 0.001 = 0.16
plot: sqrt(p*(1 - p)/N) | label: standard deviation of the estimate | samples: 400
readout: trials for 1% relative error = ceil((1 - p)/(p*0.0001)) | digits: 7
```

::: predict
## A test catches 95% of faulty boards and false-alarms on 5% of good ones. Faults affect 1% of boards. A board is flagged. What is the chance it's really faulty?

- [ ] 95%
- [ ] About 50%
- [x] About 16%
- [ ] 1%

::: reveal
About 16%. Out of 10 000 boards, 100 are faulty and 95 of them are flagged; of the 9900 good ones, 495 are flagged too. So only $\frac{95}{590} = 16\%$ of flags are real. A simulation of a million boards confirms it. When faults are rare, most alarms are false, however good the test sounds.
:::
:::

::: nameit
## Simulating with NumPy

- `rng = np.random.default_rng(seed)` makes a reproducible generator.
- `rng.random(n) < p` gives `n` independent events, each true with probability `p`.
- `rng.integers(0, k, shape)` draws whole numbers below `k`.
- Averaging a boolean array, `mask.mean()`, estimates a probability; `x[mask].mean()` estimates a conditional average, keeping only the trials where the condition held.

## How many trials

An estimate from $N$ trials has standard deviation $\sqrt{p(1 - p)/N}$, so a probability near 0.5 is known to about 0.1% after a million trials, and one near $10^{-4}$ only to 10%. Set $N$ from the precision you need before running.
:::

::: example
## Estimate the birthday probability for 23 people by simulation.

::: solution
1. **Draw the groups.** Draw 100 000 groups of 23 birthdays with `rng.integers(0, 365, (100000, 23))`.
2. **Look for a match.** Sort each row and check for any two equal neighbors.
3. **Compare with the exact value.** One run gives 0.507, matching the exact 0.5073 to within the expected spread of
   $$\sqrt{0.25/10^5} = 0.0016$$

**Answer:** the simulation gives about 0.507, in line with the exact 0.5073.
:::
:::

::: example
## Simulate the fault test: 1% faulty, 95% detection, 5% false alarms. What fraction of flagged boards are faulty?

::: solution
1. **Draw the faults.** For a million boards, draw `fault = rng.random(N) < 0.01`.
2. **Draw the flags.** Flag faulty boards with probability 0.95 and good ones with probability 0.05.
3. **Count the faulty among the flagged.** The fraction comes out 0.162.
4. **Compare with Bayes's rule.**
   $$\frac{0.0095}{0.0095 + 0.0495} = 0.161$$

**Answer:** the simulation finds 0.162 of flagged boards faulty, against 0.161 from Bayes's rule.
:::
:::

::: check
given: p = 0.01 | 0.1 | 0.3; N = 10000 | 1000000
answer: sqrt(p*(1 - p)/N)
tolerance: 0.5%

## A simulation estimates a probability near {p} from {N} trials. What is the estimate's standard deviation?

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

::: misses
- [p/sqrt(N)] Use $\sqrt{p(1 - p)/N}$.
- [any] Not yet. It's the standard error of a proportion.
:::
:::

::: check
given: s = 0.9 | 0.99; f = 0.01 | 0.05; q = 0.001 | 0.01
answer: s*q/(s*q + f*(1 - q))
tolerance: 0.5%

## A test detects {s} of faults and false-alarms on {f} of good boards; faults affect {q} of boards. What fraction of flagged boards are faulty?

::: right
Right. {answer}.
:::

::: misses
- [s] That's the detection rate, the chance of a flag given a fault, not the reverse.
- [any] Not yet. Use Bayes's rule.
:::
:::

::: check
kind: python

## Simulate 100 000 groups of 23 birthdays with `rng = np.random.default_rng(1)` and set `p_shared` to the fraction with at least one shared birthday.

```python starter
import numpy as np

p_shared = 0.0
print(p_shared)
```

```python solution
import numpy as np

rng = np.random.default_rng(1)
b = np.sort(rng.integers(0, 365, (100000, 23)), axis=1)
p_shared = np.mean((np.diff(b, axis=1) == 0).any(axis=1))
print(p_shared)
```

```python tests
assert abs(p_shared - 0.5073) < 0.006, f"The exact answer is 0.5073; the simulation should be within 0.006; got {p_shared}."
```

::: right
Right. Sorting puts equal birthdays next to each other, so one comparison per neighbor finds them.
:::
:::

::: check
kind: python

## Simulate a million boards: faulty with probability 0.01, flagged with probability 0.95 if faulty and 0.05 if good. Set `post` to the fraction of flagged boards that are faulty, and `bayes` to Bayes's formula.

```python starter
import numpy as np

post = bayes = 0.0
print(post, bayes)
```

```python solution
import numpy as np

rng = np.random.default_rng(2)
N = 10**6
fault = rng.random(N) < 0.01
flag = np.where(fault, rng.random(N) < 0.95, rng.random(N) < 0.05)
post = fault[flag].mean()
bayes = 0.95 * 0.01 / (0.95 * 0.01 + 0.05 * 0.99)
print(post, bayes)
```

```python tests
assert abs(bayes - 0.16102) < 1e-4, f"Bayes gives 0.161; got {bayes}."
assert abs(post - bayes) < 0.01, f"The simulation should agree within 0.01; got {post}."
```

::: right
Right. About one flag in six is a real fault: the simulation and Bayes agree.
:::
:::

::: check
kind: python

## Three channels each work with probability 0.9, independently, and the system works if at least two do. Simulate a million systems and set `sim`, and set `formula` to $3r^2 - 2r^3$.

```python starter
import numpy as np

sim = formula = 0.0
print(sim, formula)
```

```python solution
import numpy as np

rng = np.random.default_rng(3)
works = rng.random((10**6, 3)) < 0.9
sim = np.mean(works.sum(axis=1) >= 2)
r = 0.9
formula = 3 * r**2 - 2 * r**3
print(sim, formula)
```

```python tests
assert abs(formula - 0.972) < 1e-12, "3r^2 - 2r^3 = 0.972 for r = 0.9."
assert abs(sim - 0.972) < 0.001, f"The simulated reliability should be within 0.001 of 0.972; got {sim}."
```

::: right
Right. 97.2% against one channel's 90%: voting turns three mediocre channels into a good system.
:::
:::

::: check
kind: python

## Each of 500 packets is lost independently with probability 0.001. Simulate 100 000 such batches and set `sim` to the fraction with at least one loss, and `exact` to the formula.

```python starter
import numpy as np

sim = exact = 0.0
print(sim, exact)
```

```python solution
import numpy as np

rng = np.random.default_rng(4)
losses = rng.binomial(500, 0.001, 100000)
sim = np.mean(losses > 0)
exact = 1 - 0.999**500
print(sim, exact)
```

```python tests
assert abs(exact - 0.39362) < 1e-4, f"1 - 0.999^500 = 0.3936; got {exact}."
assert abs(sim - exact) < 0.006, f"The simulation should be within 0.006; got {sim}."
```

::: right
Right. A 0.1% loss rate still hits nearly 40% of 500-packet batches: rare events add up.
:::
:::

::: check
kind: python

## An 8-bit word has each bit flipped with probability 0.01, and a code corrects any single flip. Set `exact` to the chance a word is decoded correctly (at most one flip), and `sim` to a simulation over 10⁶ words.

```python starter
import numpy as np

exact = sim = 0.0
print(exact, sim)
```

```python solution
import numpy as np

exact = 0.99**8 + 8 * 0.01 * 0.99**7
rng = np.random.default_rng(5)
flips = rng.binomial(8, 0.01, 10**6)
sim = np.mean(flips <= 1)
print(exact, sim)
```

```python tests
assert abs(exact - 0.997310) < 1e-6, f"The exact chance is 0.99731; got {exact}."
assert abs(sim - exact) < 0.0005, f"The simulation should agree within 0.0005; got {sim}."
```

::: right
Right. Correcting one error cuts the word error rate from 7.7% to 0.27%.
:::
:::

::: explain
## A simulation and a formula disagree by more than the simulation's standard deviation. What should you suspect?

::: model
First, check whether the disagreement is really significant: an estimate from $N$ trials is off by more than one standard deviation about a third of the time, and by more than three only 0.3% of the time. A gap of several standard deviations means a real mistake. It can be in the formula, such as treating dependent events as independent or forgetting that two events overlap, or in the simulation, such as a wrong probability in the random draw, drawing the same random numbers for things that should be independent, or estimating the wrong conditional (counting all trials instead of only those where the condition held). Running both on a simpler case where the answer is known usually reveals which.
:::
:::

::: practice

::: check
given: p = 0.0001..0.5; N = 1000..10000000
answer: sqrt(p*(1 - p)/N)
tolerance: 0.5%

## Standard deviation of a probability estimate near {p} from {N} trials?

::: misses
- [any] $\sqrt{p(1 - p)/N}$.
:::
:::

::: check
given: r = 0.5..0.999
answer: 3*r^2 - 2*r^3
tolerance: 0.5%

## Reliability of 2-of-3 voting with channels of reliability {r}?

::: misses
- [any] $3r^2 - 2r^3$.
:::
:::
:::
