TExcelTAD
Home › Probability Theory › Monte Carlo Methods

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 θ=E[g(X)]\theta = E[g(X)], draw independent samples X1,…,XnX_1, \ldots, X_n and average:

θ^n=1n∑i=1ng(Xi),standard error≈sn\hat\theta_n = \frac{1}{n}\sum_{i=1}^{n} g(X_i), \qquad \text{standard error} \approx \frac{s}{\sqrt{n}}

An integral ∫Ah(x) dx\int_A h(x)\,dx is an expectation in disguise: vol⁡(A)⋅E[h(U)]\operatorname{vol}(A) \cdot E[h(U)] with UU uniform on AA. The error shrinks like 1/n1/\sqrt{n} in any dimension, which is why Monte Carlo beats grid methods in high dimensions, where a grid with 10 points per axis needs 10d10^d points.

python · try it yourself
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 dd grows (0.25%0.25\% in 10 dimensions), so plain sampling wastes most points: the relative error grows. That motivates smarter sampling.

Variance reduction

The error is σ/n\sigma/\sqrt{n}, so reducing σ\sigma is as good as taking more samples:

  • Antithetic variates: pair each UU with 1−U1 - U; for monotone functions the errors cancel partly.
  • Control variates: subtract a correlated quantity with known mean.
  • Importance sampling: sample from a distribution qq that puts more points where gg matters, and reweight by p/qp/q. Essential for rare events.
python · try it yourself
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 Pr⁡[Z>5]\Pr[Z > 5] for a standard normal ZZ? It is about 2.9×10−72.9 \times 10^{-7}, 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 ϕ(x)/ϕ(x−5)=e−5x+12.5\phi(x)/\phi(x - 5) = e^{-5x + 12.5} gives an accurate answer with a few thousand samples:

python · try it yourself
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 min⁡(1,π(new)/π(old))\min(1, \pi(\text{new})/\pi(\text{old})), 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

2/n=0.012/\sqrt{n} = 0.01 gives n=200\sqrt{n} = 200.

Exercise 2: Why antithetic works

Why does pairing UU with 1−U1 - U reduce the variance for g(u)=eug(u) = e^u?

Answer

g(U)g(U) and g(1−U)g(1 - U) are negatively correlated, so their average varies less.

Solution

Var⁡(A+B2)=Var⁡A+Var⁡B+2Cov⁡(A,B)4\operatorname{Var}\left(\frac{A + B}{2}\right) = \frac{\operatorname{Var}A + \operatorname{Var}B + 2\operatorname{Cov}(A, B)}{4}. For increasing gg, a large UU gives large g(U)g(U) but small g(1−U)g(1 - U): the covariance is negative.

Exercise 3: Metropolis (code)

Use the Metropolis algorithm to sample from the density proportional to e−x4e^{-x^4} and estimate E[X2]E[X^2]. The exact value is Γ(3/4)/Γ(1/4)≈0.3380\Gamma(3/4)/\Gamma(1/4) \approx 0.3380.

Answer

About 0.338.

Solution
python · try it yourself
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…

  1. 1/n1/n
  2. 1/n1/\sqrt{n}
  3. 1/n21/n^2
  4. e−ne^{-n}

Importance sampling is most useful for…

  1. very common events
  2. rare events
  3. deterministic functions
  4. discrete uniform distributions