---
title: Monte Carlo methods
heading: Integrating by sampling at random, with an error that shrinks the same way in any dimension
eyebrow: A13 · Lesson 48 · Monte Carlo methods
xp: 40
---

::: hook
A circuit has 20 components, each within its tolerance. What fraction of built boards will meet the spec? That's an integral over a 20-dimensional box, and a grid with just 10 points per axis would need $10^{20}$ circuit simulations. **Monte Carlo** draws random component values, simulates, and counts. Its error shrinks only as $1/\sqrt N$, slowly, but that rate doesn't depend on the dimension at all, which is why yield analysis, bit-error-rate simulation and radiation transport all run on it. A11 used Monte Carlo to explore probability; here it's a numerical method, with an error bar you can compute and tricks that shrink it.
:::

::: play
- The running mean of $e^{-U^2}$ for uniform random U estimates $\int_0^1e^{-x^2}dx = 0.746824$ (the marked line). Each trial adds one random sample.
- Early on the estimate wanders a lot; it settles as $1/\sqrt n$. The readouts give the estimate and its standard error, $s/\sqrt n$, computed from the samples themselves.
- Raise n by 100: the error bar shrinks by only 10. Each extra digit costs 100 times the samples.
:::
:::

```sim plot
view: random
x: f = 0..1.1
slider: n = 100..100000 = 1000 log
sample: exp(-rand(1)^2) | mean: M | sd: S
trials: n
bins: 40
trace: 2000 | running
marker: trace = 0.746824 | label: exact
readout: estimate = M
readout: standard error s/√n = S/sqrt(n)
readout: actual error = M - 0.746824
```

::: predict
## A Monte Carlo estimate has a standard error of 0.002 with $10^4$ samples. How many samples bring it to 0.0002?

- [ ] $10^5$
- [x] $10^6$
- [ ] $10^8$
- [ ] $2 \times 10^4$

::: reveal
$10^6$: the error goes as $1/\sqrt N$, so 10 times smaller needs 100 times the samples. That's the price of Monte Carlo, and also why it's used only where nothing else works: in many dimensions, or when the "integrand" is a whole simulation.
:::
:::

::: nameit
## Monte Carlo integration

For $I = \int_\Omega f\,dV$ over a region of volume V, draw $x_1, \ldots, x_N$ uniformly in Ω:

$$\hat I = \frac VN\sum f(x_i), \qquad \text{standard error} \approx \frac{V\,s}{\sqrt N}$$

where s is the samples' standard deviation. The error is $O(N^{-1/2})$ in **any** dimension. A grid rule of order p in d dimensions, with N points in all, has error $O(N^{-p/d})$: better than Monte Carlo when $p/d > \frac12$, worse in high dimensions.

## Probabilities and yield

An event's probability is the mean of an indicator (1 if it happens, 0 if not). With $\hat p$ from N trials, the standard error is $\sqrt{\hat p(1 - \hat p)/N}$. To see about 100 occurrences of an event of probability p you need about 100/p trials, which is why simulating a bit error rate of $10^{-9}$ by brute force takes $10^{11}$ bits.

## Reducing the variance

- **Antithetic pairs:** use both U and 1 − U; for monotone f their errors partly cancel.
- **Control variates:** subtract a similar function g with a known integral: estimate $\int(f - g) + \int g$.
- **Importance sampling:** draw from a density q concentrated where f matters and average $f/q$. Shifting the noise toward the decision threshold is how bit error rates of $10^{-12}$ are simulated in seconds.
- **Quasi-Monte Carlo:** low-discrepancy sequences (Halton, Sobol) fill the region more evenly than random points; error about $(\log N)^d/N$ for smooth integrands.

## Random numbers

Use a good generator (PCG, Mersenne Twister, NumPy's default), and **seed** it so a run can be repeated exactly.
:::

::: example
## Estimate $\int_0^1e^{-x^2}dx$ with $10^4$ samples. How accurate is it?

::: solution
1. **The standard error.** The integrand's standard deviation over [0, 1] is 0.201, so
   $$0.201/\sqrt{10^4} = 0.0020$$
   about two good digits.
2. **For an error of $10^{-4}$.** You'd need
   $$(0.201/10^{-4})^2 = 4 \times 10^6$$
   samples.
3. **Compare with Simpson.** Simpson's rule with 10 intervals gets $10^{-6}$. In one dimension, Monte Carlo is a poor choice.

**Answer:** the standard error is 0.0020, about two good digits.
:::
:::

::: example
## A yield simulation passes 9530 of 10 000 boards. What's the yield and its uncertainty?

::: solution
1. **The estimate.** $\hat Y = 0.953$.
2. **Its standard error.**
   $$\sqrt{0.953 \times 0.047/10\,000} = 0.0021$$
3. **Report.** Report 95.3% ± 0.4% (two standard errors).

**Answer:** the yield is 95.3% ± 0.4%.
:::
:::

::: example
## Estimate $\int_0^1e^x\,dx$ by Monte Carlo with antithetic pairs $\frac{e^U + e^{1 - U}}{2}$. How much does that help?

::: solution
1. **One sample's variance.**
   $$\begin{aligned} &\frac{e^2 - 1}{2} - (e - 1)^2 \\ &= 0.2420 \end{aligned}$$
2. **The covariance.** The pair's two halves are negatively correlated:
   $$\begin{aligned} &\text{Cov}(e^U, e^{1-U}) \\ &= e - (e - 1)^2 \\ &= -0.2342 \end{aligned}$$
3. **The pair average's variance.**
   $$\frac{0.2420 - 0.2342}{2} = 0.0039$$
4. **Compare.** Two independent samples would have variance $0.2420/2 = 0.121$, so for the same number of evaluations the antithetic pairs cut the variance 31-fold.
5. **Why it works.** $e^x$ is monotone: when one half of a pair is high, the other is low.

**Answer:** the pair average's variance is 0.0039, 31 times less than for two independent samples.
:::
:::

::: check
given: s = 0.2 | 1.5 | 30; N = 1000 | 100000
answer: s/sqrt(N)
tolerance: 0.5%

## Samples of a Monte Carlo integrand have standard deviation {s}. What's the standard error of the mean of {N} of them (unit volume)?

::: right
Right. $s/\sqrt N$ = {answer}.
:::

::: misses
- [s/N] The error falls as $1/\sqrt N$, not $1/N$.
- [any] Not yet. $s/\sqrt N$.
:::
:::

::: check
given: s = 0.2 | 2; e = 0.001 | 0.00001
answer: (s/e)^2
tolerance: 0.5%

## How many samples bring a Monte Carlo standard error to {e}, if the integrand's standard deviation is {s}?

::: right
Right. $(s/\varepsilon)^2$ = {answer}.
:::

::: misses
- [s/e] Squared: halving the error takes four times the samples.
- [any] Not yet. Solve $s/\sqrt N = \varepsilon$.
:::
:::

::: check
given: p = 0.001 | 0.000001 | 0.000000001; k = 100 | 1000
answer: k/p
tolerance: 0.5%

## About how many trials does it take to see {k} occurrences of an event with probability {p}?

::: right
Right. $k/p$ = {answer}.
:::

::: misses
- [any] Not yet. Expect pN occurrences in N trials.
:::
:::

::: check
given: Y = 0.95 | 0.8 | 0.99; N = 1000 | 10000
answer: sqrt(Y*(1 - Y)/N)
tolerance: 0.5%

## A simulation estimates a yield of {Y} from {N} trials. What's its standard error?

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

::: misses
- [Y/sqrt(N)] For a proportion, the standard deviation is $\sqrt{Y(1 - Y)}$.
- [any] Not yet. $\sqrt{\hat p(1 - \hat p)/N}$.
:::
:::

::: check
given: p = 2 | 4; d = 3 | 10 | 20
answer: -p/d
tolerance: 0.5%

## A grid rule of order {p} in {d} dimensions has error $O(N^q)$ in the total number of points N. What's q?

::: right
Right. $q = -p/d$ = {answer}, against Monte Carlo's −0.5.
:::

::: misses
- [-p] That's per axis; with N points in d dimensions each axis gets only $N^{1/d}$.
- [any] Not yet. Each axis has $N^{1/d}$ points, so $h \propto N^{-1/d}$.
:::
:::

::: check
kind: choice

## A link must be verified at a bit error rate of $10^{-12}$. Which simulation approach is practical?

- [ ] Brute-force Monte Carlo with $10^{12}$ bits
- [x] Importance sampling: draw the noise from a shifted distribution that makes errors common, and weight each by the likelihood ratio
- [ ] A Simpson's-rule integral over the noise in every dimension
- [ ] Ten bits, checked carefully

::: misses
- [1] You'd need about $10^{14}$ bits to see 100 errors.
- [3] The noise space has as many dimensions as the bits and taps involved.
- [4] You'd see no errors and learn nothing.
:::
:::

::: check
kind: parts
given: V = 0.242 | 1; C = -0.2 | -0.1

## Each sample has variance {V}, and the two halves of an antithetic pair have covariance {C}.

::: part
answer: (V + C)/2
tolerance: 0.5%

### What is the variance of the pair's average?

::: misses
- [V/2] That ignores the covariance, which is the point.
- [any] $\text{Var}\frac{X + Y}{2} = \frac{V + C}{2}$ for equal variances.
:::
:::

::: part
answer: V/(V + C)
tolerance: 0.5%

### By what factor does that beat two independent samples?

::: misses
- [any] Compare with $V/2$.
:::
:::
:::

::: check
kind: derivation
vars: s = 0.1..2, e = 0.001..0.1, p = 0.001..0.2, r = 0.01..0.2

## Monte Carlo sample sizes.

::: step
answer: (s/e)^2

### How many samples bring a standard error to e, with per-sample standard deviation s?
:::

::: step
answer: (1 - p)/(p*r^2)

### How many trials estimate a probability p to relative error r?
:::

::: right
Right. Rare events are expensive: the count grows as $1/p$.
:::
:::

::: explain
## Why doesn't Monte Carlo's error depend on the number of dimensions, when a grid's does?

::: model
A Monte Carlo estimate is the mean of N independent random samples of the integrand, and the standard error of a mean is the samples' standard deviation divided by $\sqrt N$. Nothing in that depends on how many coordinates each sample has: the dimension affects only how much the integrand varies, its standard deviation, not the rate. A grid with N points in d dimensions has only $N^{1/d}$ points along each axis, so its spacing shrinks slowly in high dimensions and its error, a power of the spacing, falls as $N^{-p/d}$. Past a handful of dimensions that's slower than $N^{-1/2}$.
:::
:::

::: practice

::: check
given: s = 0.5 | 4; N = 400 | 250000
answer: s/sqrt(N)
tolerance: 0.5%

## Standard error, s = {s}, N = {N}?

::: misses
- [any] $s/\sqrt N$.
:::
:::

::: check
given: s = 0.1 | 3; e = 0.01 | 0.0001
answer: (s/e)^2
tolerance: 0.5%

## Samples for error {e} with s = {s}?

::: misses
- [any] $(s/\varepsilon)^2$.
:::
:::

::: check
given: Y = 0.9 | 0.999; N = 500 | 50000
answer: sqrt(Y*(1 - Y)/N)
tolerance: 0.5%

## Yield standard error, {Y} from {N} trials?

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