Monte Carlo Methods
Monte Carlo methods estimate a quantity by averaging random samples. They are how physicists simulate particles, how banks price options and measure risk, how renderers draw realistic light, and how Bayesian models are fitted. The idea is the law of large numbers put to work; the craft is making the error small with as few samples as possible.
The basic estimator
To estimate , draw independent samples and average:
An integral is an expectation in disguise: with uniform on . The error shrinks like in any dimension, which is why Monte Carlo beats grid methods in high dimensions, where a grid with 10 points per axis needs points.
import numpy as np
from math import gamma, pi
rng = np.random.default_rng(1)
n = 200_000
for d in [2, 3, 5, 10]:
pts = rng.uniform(-1, 1, size=(n, d))
inside = (np.sum(pts ** 2, axis=1) <= 1).mean()
est = inside * 2 ** d
exact = pi ** (d / 2) / gamma(d / 2 + 1)
se = 2 ** d * np.sqrt(inside * (1 - inside) / n)
print(f"d={d:2d}: volume of unit ball ~ {est:.4f} +- {1.96 * se:.4f} exact {exact:.4f}")d= 2: volume of unit ball ~ 3.1386 +- 0.0072 exact 3.1416
d= 3: volume of unit ball ~ 4.1906 +- 0.0175 exact 4.1888
d= 5: volume of unit ball ~ 5.2571 +- 0.0520 exact 5.2638
d=10: volume of unit ball ~ 2.6675 +- 0.2288 exact 2.5502
The ball fills a shrinking fraction of the cube as grows ( in 10 dimensions), so plain sampling wastes most points: the relative error grows. That motivates smarter sampling.
Variance reduction
The error is , so reducing is as good as taking more samples:
- Antithetic variates: pair each with ; for monotone functions the errors cancel partly.
- Control variates: subtract a correlated quantity with known mean.
- Importance sampling: sample from a distribution that puts more points where matters, and reweight by . Essential for rare events.
import numpy as np
rng = np.random.default_rng(2)
n = 10_000
g = lambda u: np.exp(u) # E[e^U] = e - 1
exact = np.e - 1
u = rng.random(n)
plain = g(u)
anti = (g(u[: n // 2]) + g(1 - u[: n // 2])) / 2 # same number of function calls
control = g(u) - 1.69 * (u - 0.5) # U has known mean 1/2
for name, x in [("plain", plain), ("antithetic", anti), ("control variate", control)]:
print(f"{name:16s} estimate {x.mean():.5f} std error {x.std() / np.sqrt(len(x)):.5f}")
print("exact:", round(exact, 5))plain estimate 1.71953 std error 0.00496
antithetic estimate 1.71939 std error 0.00088
control variate estimate 1.71950 std error 0.00063
exact: 1.71828
Both tricks cut the standard error by a large factor at no extra cost.
Importance sampling for rare events
What is for a standard normal ? It is about , so plain sampling with a million points sees almost no hits. Sampling instead from a normal centred at 5 and reweighting by the density ratio gives an accurate answer with a few thousand samples:
import numpy as np
from math import erfc, sqrt
rng = np.random.default_rng(3)
exact = 0.5 * erfc(5 / sqrt(2))
z = rng.standard_normal(1_000_000)
print("plain, 1,000,000 samples:", (z > 5).mean())
x = rng.normal(5, 1, 10_000)
w = np.exp(-5 * x + 12.5)
est = np.mean((x > 5) * w)
print(f"importance sampling, 10,000 samples: {est:.3e} exact {exact:.3e}")plain, 1,000,000 samples: 0.0
importance sampling, 10,000 samples: 2.865e-07 exact 2.867e-07
Markov chain Monte Carlo
When the distribution can only be evaluated up to a constant (a Bayesian posterior), MCMC builds a Markov chain whose stationary distribution is the target. The Metropolis algorithm proposes a random move and accepts it with probability , which satisfies detailed balance. Averages along the chain converge to expectations under the target.
In software
Monte Carlo is the engine of path tracing in film rendering, of Value-at-Risk in finance, of reliability estimates for networks, of AlphaGo-style tree search, and of probabilistic programming (Stan, PyMC). Good practice: seed the generator, report a standard error, and test the estimator on a case with a known answer.
Exercises
Exercise 1: Samples needed
A Monte Carlo estimate has per-sample standard deviation 2. How many samples give a standard error of 0.01?
Answer
40,000.
Solution
gives .
Exercise 2: Why antithetic works
Why does pairing with reduce the variance for ?
Answer
and are negatively correlated, so their average varies less.
Solution
. For increasing , a large gives large but small : the covariance is negative.
Exercise 3: Metropolis (code)
Use the Metropolis algorithm to sample from the density proportional to and estimate . The exact value is .
Answer
About 0.338.
Solution
import math
import random
rng = random.Random(4)
target = lambda x: math.exp(-x ** 4)
x, total, n, burn = 0.0, 0.0, 400_000, 10_000
for i in range(n + burn):
y = x + rng.uniform(-1, 1)
if rng.random() < target(y) / target(x):
x = y
if i >= burn:
total += x * x
print(round(total / n, 4), round(math.gamma(0.75) / math.gamma(0.25), 4))0.3409 0.338
Test yourself
The error of a plain Monte Carlo estimate decreases like…
Importance sampling is most useful for…
- very common events
- rare events
- deterministic functions
- discrete uniform distributions