Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Monte Carlo Methods

Open in Colab

Monte Carlo methods use randomness to solve deterministic problems. Most of them compute an integral written as an expectation,

E[f(X)]=∫f(x) p(x) dx,\mathbb E[f(X)] = \int f(x)\, p(x)\, dx,

where XX is a random variable with probability density pp, a non-negative function that integrates to 1. If X1,X2,…X_1, X_2, \dots are independent samples of XX, the law of large numbers says that their sample mean converges to the expectation:

f^n=1n∑i=1nf(Xi)  →  E[f(X)]as n→∞.\hat f_n = \frac1n \sum_{i=1}^n f(X_i) \;\to\; \mathbb E[f(X)] \quad\text{as } n \to \infty.

Example: estimating π\pi

The unit disk DD has area π\pi and lies inside the square [−1,1]2[-1, 1]^2, which has area 4. If UU is uniformly distributed on the square, then

π=4 P(U∈D)=4 E[χD(U)],\pi = 4\, P(U \in D) = 4\, \mathbb E[\chi_D(U)],

where the indicator function χD\chi_D is 1 inside the disk and 0 outside. So π\pi is about 4 times the fraction of random points in the square that land in the disk.

The error of Monte Carlo

The estimate f^n\hat f_n is random, and so is its error. Since the XiX_i are independent, the variance of their sum is the sum of their variances:

Var(f^n)=1n2∑i=1nVar(f(Xi))=σ2n,σ2=Var(f(X)).\mathrm{Var}(\hat f_n) = \frac{1}{n^2} \sum_{i=1}^n \mathrm{Var}(f(X_i)) = \frac{\sigma^2}{n}, \qquad \sigma^2 = \mathrm{Var}(f(X)).

The typical (root-mean-square) error is therefore σ/n\sigma/\sqrt n. The central limit theorem says for large nn, f^n\hat f_n is approximately normally distributed, with mean E[f(X)]\mathbb E[f(X)] and standard deviation σ/n\sigma/\sqrt n.

The rate n−1/2n^{-1/2} is slow, since each additional correct digit costs 100 times as many samples. But it doesn’t depend on the dimension of xx or on the smoothness of ff. A quadrature rule of order pp that uses nn points in dd dimensions has an error of O(n−p/d)O(n^{-p/d}), so Monte Carlo is more accurate when d>2pd > 2p, and integrals in many dimensions are almost always computed by Monte Carlo.

We check the central limit theorem by repeating the π\pi experiment 2000 times. Each sample 4χD(U)4\chi_D(U) is 4 with probability π/4\pi/4 and 0 otherwise, so σ2=16⋅π4(1−π4)\sigma^2 = 16 \cdot \frac{\pi}{4}\left(1 - \frac{\pi}{4}\right).

Finally, let’s look at how the error converges with nn:

Error bars

We usually don’t know σ\sigma, but we can estimate it from the same samples by the sample standard deviation ss. The standard error s/ns/\sqrt n then estimates the error, and by the central limit theorem

f^n±1.96 sn\hat f_n \pm 1.96\, \frac{s}{\sqrt n}

is an approximate 95% confidence interval (see SciPy stats). A Monte Carlo estimate should always be reported with an error bar like this, and it costs nothing extra to compute.

About 95% of these intervals should contain π\pi. We check with the 2000 repetitions above:

The error bar is only as good as the estimate ss of σ\sigma. It can be badly wrong when f(X)f(X) is very large with a small probability, as in an example below.

Importance sampling

Suppose we want the integral of a sharply peaked function,

I=∫−∞∞e−104x2 dx=π100.I = \int_{-\infty}^\infty e^{-10^4 x^2}\, dx = \frac{\sqrt\pi}{100}.

The integrand is negligible outside [−1,1][-1, 1], so we could write I=2 E[f(U)]I = 2\,\mathbb E[f(U)] with UU uniform on [−1,1][-1, 1]. But the peak has a width of about 0.01, so almost every sample misses it, and f(U)f(U) has a large variance compared with its mean.

Instead, draw samples from a density qq that puts more of them where ff is large, and correct for this with a weight:

I=∫f(x)q(x) q(x) dx=E ⁣[f(Y)q(Y)],Y∼q.I = \int \frac{f(x)}{q(x)}\, q(x)\, dx = \mathbb E\!\left[\frac{f(Y)}{q(Y)}\right], \qquad Y \sim q.

This is importance sampling. The estimate is unbiased for any density qq that is positive wherever ff is nonzero, but its variance depends on qq. We try normal distributions qq with several standard deviations ss, and measure the root-mean-square error over 50 repetitions.

The best of these proposals is s=0.01s = 0.01. Its error is more than 20 times smaller than that of uniform sampling. The choice s=1/2⋅104≈0.007s = 1/\sqrt{2 \cdot 10^4} \approx 0.007 would be even better. Of course, normalizing qq requires knowing II, but we should aim for qq to have roughly the shape of ∣f∣|f|.

Markov chain Monte Carlo

Often we want E[f(X)]\mathbb E[f(X)] for a density we can’t sample from directly. A common case, in statistical physics and in Bayesian statistics, is

p(x)=e−V(x)Z,Z=∫e−V(x) dx,p(x) = \frac{e^{-V(x)}}{Z}, \qquad Z = \int e^{-V(x)}\, dx,

where we can evaluate VV, but the normalizing constant ZZ is unknown, because it is itself a hard integral in high dimensions.

Markov chain Monte Carlo (MCMC) generates a sequence X0,X1,X2,…X_0, X_1, X_2, \dots in which each Xi+1X_{i+1} is drawn at random given only XiX_i. Such a sequence is a Markov chain. We design the chain so that its stationary distribution is pp: after many steps the XiX_i are distributed according to pp, and averages along the chain converge to E[f(X)]\mathbb E[f(X)].

The Metropolis algorithm

Starting from XiX_i:

  1. Propose a move Y=Xi+δ ξY = X_i + \delta\, \xi, where ξ∼N(0,1)\xi \sim \mathcal N(0, 1) and δ\delta is a step size.

  2. Accept it, Xi+1=YX_{i+1} = Y, with probability min⁡(1,p(Y)/p(Xi))\min\left(1, p(Y)/p(X_i)\right). Otherwise reject it and stay put: Xi+1=XiX_{i+1} = X_i.

Moves to higher probability are always accepted, and moves to lower probability only sometimes. The ratio p(Y)/p(Xi)=eV(Xi)−V(Y)p(Y)/p(X_i) = e^{V(X_i) - V(Y)} doesn’t involve ZZ. This is a specialization of the Metropolis-Hastings algorithm, you can check the stationary probability is pp.

We sample from p(x)∝e−V(x)p(x) \propto e^{-V(x)} with V(x)=x4−x2V(x) = x^4 - x^2, which has two shallow wells at x=±1/2x = \pm 1/\sqrt 2, and compare with the exact density, normalized by quadrature.

Choosing the step size

Successive states of a Markov chain are correlated, and the step size δ\delta controls how strongly. Trace plots of chains started far from the wells, at x0=3x_0 = 3, show the trade-off.

  • With a small step, almost every proposal is accepted, but the chain moves like a random walk with tiny steps. It needs many steps just to reach the wells from x0=3x_0 = 3, and it rarely moves from one well to the other.

  • With a large step, almost every proposal lands where pp is tiny and is rejected, so the chain is stuck for long stretches.

  • A moderate step explores the distribution quickly.

The first part of a chain, before it has forgotten its starting point, doesn’t sample pp and should be discarded as burn-in.

Exercises

Exercise 1

The unit ball in dd dimensions has volume πd/2/Γ(d/2+1)\pi^{d/2} / \Gamma(d/2 + 1) (scipy.special.gamma). Estimate it as 2d2^d times the fraction of n=106n = 10^6 uniform points in [−1,1]d[-1, 1]^d that land in the ball, for d=2,4,…,16d = 2, 4, \dots, 16. Report each estimate with an error bar, and plot the relative error against dd. Why does the relative error grow with dd, even though the rate n−1/2n^{-1/2} doesn’t depend on the dimension?