Search

Search papers and lessons

Monte Carlo Method

Level 2 · 12 min read

Monte Carlo methods answer hard questions about random or complicated systems by averaging many random samples, and the error shrinks as one over the square root of the sample count.

On this page

  • Colour = topic mix
  • Probability
  • Discrete math
  • Sampling
  • Sign in to see your progress

TL;DR

A Monte Carlo method answers a question about a random or complicated system by simulating it many times and averaging the results. If you need an area, an average or a probability and have no formula for it, draw random inputs, evaluate the quantity you care about on each one, and take the mean. The law of large numbers says that mean settles on the right answer, and the error shrinks like one over the square root of the number of samples.

Where you'll see it: pricing financial options, estimating the expectations inside variational autoencoders, rendering images by light-path tracing, and checking how a statistical test behaves when the textbook formula does not apply.

Intuition

Guessing by sampling

Suppose you want the area of a lake on a map and have no formula for its outline. Drop pebbles at random across a rectangle that contains the lake, count how many land in the water, and multiply the fraction by the rectangle's area. The pebbles are random points, and the fraction that lands in the lake estimates the fraction of the rectangle that is lake. More pebbles give a better estimate. That is the whole method: replace a calculation you cannot do with a random experiment you can run.

The name is a nod to the casino in Monte Carlo and the randomness of games of chance. The idea is older than the name. Buffon's needle, published in 1777, estimated π by dropping a needle onto lined floorboards. The method became a general tool in the mid-1940s, when Stanislaw Ulam and John von Neumann used it on neutron diffusion problems at Los Alamos.

Why bother with randomness at all? Many quantities are integrals in disguise, and a grid of points stops working as the number of dimensions grows. A grid with 10 points along each of 10 axes already has 10 billion points. Random samples do not have that problem: the error shrinks at the same rate whatever the dimension. That is the reason the method matters in machine learning, where the integrals are over thousands of dimensions.

Here is the idea on a one-dimensional integral. We want the area under f(x)=x2f(x) = x^2 between 0 and 1. Each random point xix_i gives one value f(xi)f(x_i), and the average of those values estimates the average height of the curve, which is the area.

00.20.40.60.8100.20.40.60.81xf(x)
  • f(x) = x^2
Four random inputs and their function values. The average of the four heights estimates the average height of the curve over [0, 1], which equals the area.

The steps are the same for any problem of this kind:

flowchart LR
  A[Write the quantity as an expectation] --> B[Draw random samples]
  B --> C[Evaluate the function on each sample]
  C --> D[Average the values]
  D --> E[Report the estimate with an error bar]

The math

The estimator

Suppose we want μ=E[f(X)]\mu = \mathbb{E}[f(X)], the expected value of ff applied to a random variable XX with density p(x)p(x). Written as an integral, this is

μ=∫f(x) p(x) dx.\mu = \int f(x)\, p(x)\, dx.

Draw nn samples x1,…,xnx_1, \dots, x_n that are independent and each distributed according to pp. The Monte Carlo estimate is their average:

Definition: Monte Carlo estimator
μ^n=1n∑i=1nf(xi).\hat{\mu}_n = \frac{1}{n} \sum_{i=1}^{n} f(x_i).

Here nn is the number of samples, and μ^n\hat{\mu}_n (read "mu-hat") is the estimate computed from them.

The estimator is unbiased. Each term f(xi)f(x_i) has expected value μ\mu, and the expected value of an average is the average of the expected values, so E[μ^n]=μ\mathbb{E}[\hat{\mu}_n] = \mu. The law of large numbers adds that μ^n\hat{\mu}_n approaches μ\mu as nn grows.

How accurate it is

Let σf2=Var(f(X))\sigma_f^2 = \mathrm{Var}(f(X)) be the variance of a single sample's value. Because the samples are independent, variances add:

Var(μ^n)=1n2∑i=1nVar(f(xi))=1n2⋅n σf2=σf2n.\begin{aligned} \mathrm{Var}(\hat{\mu}_n) &= \frac{1}{n^2} \sum_{i=1}^{n} \mathrm{Var}(f(x_i)) \\ &= \frac{1}{n^2} \cdot n\,\sigma_f^2 \\ &= \frac{\sigma_f^2}{n}. \end{aligned}

The standard error, which is the typical size of the error, is therefore

SE(μ^n)=σfn.\mathrm{SE}(\hat{\mu}_n) = \frac{\sigma_f}{\sqrt{n}}.

For large nn the central limit theorem says μ^n\hat{\mu}_n is roughly Gaussian around μ\mu, so about 95% of runs land within two standard errors of the true answer. In practice σf\sigma_f is unknown, so we estimate it from the same samples with the sample variance:

σ^f2=1n−1∑i=1n(f(xi)−μ^n)2.\hat{\sigma}_f^2 = \frac{1}{n-1} \sum_{i=1}^{n} \bigl(f(x_i) - \hat{\mu}_n\bigr)^2.

The 1/n1/\sqrt{n} rule has a practical consequence. To halve the error you need four times as many samples. To gain one more correct digit you need a hundred times as many. The rate does not depend on how many dimensions XX has, only on σf\sigma_f.

Integrals as expectations

Any integral over an interval [a,b][a, b] can be written as an expectation. Let UU be uniform on [a,b][a, b], which has density 1/(b−a)1/(b-a). Then

∫abg(x) dx=(b−a) E[g(U)],\int_a^b g(x)\, dx = (b-a)\,\mathbb{E}[g(U)],

so the estimator is b−an∑i=1ng(ui)\frac{b-a}{n} \sum_{i=1}^{n} g(u_i) for independent uniform draws uiu_i. This is the same definite integral from the calculus lesson, computed by sampling instead of by a formula.

Probabilities as expectations

A probability is the expected value of an indicator. If AA is an event and 1A(X)\mathbf{1}_A(X) equals 1 when XX is in AA and 0 otherwise, then P(X∈A)=E[1A(X)]P(X \in A) = \mathbb{E}[\mathbf{1}_A(X)]. The Monte Carlo estimate is simply the fraction of samples that fall in AA. Because each indicator is 0 or 1, its variance is p(1−p)p(1-p) with p=P(X∈A)p = P(X \in A), so

SE=p(1−p)n.\mathrm{SE} = \sqrt{\frac{p(1-p)}{n}}.

Worked examples

Example
Estimating π with five points

Take the unit square. The quarter circle x2+y2≤1x^2 + y^2 \le 1 inside it has area π/4≈0.7854\pi/4 \approx 0.7854. Draw five random points in the square and check each one.

  1. (0.2,0.9)(0.2, 0.9): 0.04+0.81=0.85≤10.04 + 0.81 = 0.85 \le 1, inside.
  2. (0.7,0.8)(0.7, 0.8): 0.49+0.64=1.13>10.49 + 0.64 = 1.13 \gt 1, outside.
  3. (0.5,0.5)(0.5, 0.5): 0.25+0.25=0.50≤10.25 + 0.25 = 0.50 \le 1, inside.
  4. (0.9,0.6)(0.9, 0.6): 0.81+0.36=1.17>10.81 + 0.36 = 1.17 \gt 1, outside.
  5. (0.1,0.3)(0.1, 0.3): 0.01+0.09=0.10≤10.01 + 0.09 = 0.10 \le 1, inside.

Three of five points are inside, so the fraction is p=0.6p = 0.6. Since the square has area 1, the circle's area is estimated as 0.60.6, and π\pi is estimated as 4×0.6=2.44 \times 0.6 = 2.4.

The error bar is large. The standard error of the fraction is 0.7854×0.2146/5≈0.184\sqrt{0.7854 \times 0.2146 / 5} \approx 0.184, so the standard error on π\pi is 4×0.184≈0.734 \times 0.184 \approx 0.73. The estimate 2.4±0.732.4 \pm 0.73 is honest but nearly useless. Five samples show the method working; shrinking that error bar takes many more samples, at the 1/n1/\sqrt{n} rate.

Example
Integrating x squared with four draws

We estimate ∫01x2 dx\int_0^1 x^2\, dx, whose exact value is 1/3≈0.33331/3 \approx 0.3333. The uniform draws are u=0.2,0.7,0.5,0.9u = 0.2, 0.7, 0.5, 0.9.

  1. Evaluate the function: f(0.2)=0.04f(0.2) = 0.04, f(0.7)=0.49f(0.7) = 0.49, f(0.5)=0.25f(0.5) = 0.25, f(0.9)=0.81f(0.9) = 0.81.
  2. Average them: (0.04+0.49+0.25+0.81)/4=1.59/4=0.3975(0.04 + 0.49 + 0.25 + 0.81)/4 = 1.59/4 = 0.3975.
  3. Estimate the sample standard deviation. The deviations from 0.3975 are −0.3575-0.3575, 0.09250.0925, −0.1475-0.1475, 0.41250.4125. Their squares sum to 0.32830.3283, so σ^f2=0.3283/3=0.1094\hat{\sigma}_f^2 = 0.3283/3 = 0.1094 and σ^f≈0.331\hat{\sigma}_f \approx 0.331.
  4. Standard error: 0.331/4≈0.1650.331/\sqrt{4} \approx 0.165.

The result is 0.398±0.1650.398 \pm 0.165. The true value 0.3330.333 is well within one standard error, so the answer is consistent with the truth. The interpretation is that four samples give a rough answer, and you should not trust the third decimal place.

Example
A rare-event probability in a realistic setting

A risk model needs P(X>2)P(X \gt 2) for a standard Gaussian XX. The exact value is 1−Φ(2)≈0.02281 - \Phi(2) \approx 0.0228. With n=10,000n = 10{,}000 samples, suppose 231 exceed 2, so the estimate is p^=0.0231\hat{p} = 0.0231.

  1. Standard error: 0.0228×0.9772/10,000≈2.23×10−6≈0.0015\sqrt{0.0228 \times 0.9772 / 10{,}000} \approx \sqrt{2.23 \times 10^{-6}} \approx 0.0015.
  2. The estimate 0.0231±0.00150.0231 \pm 0.0015 is consistent with 0.02280.0228.
  3. To cut the error tenfold, to about 0.000150.00015, you need a hundred times more samples, one million in total.

This is where plain Monte Carlo becomes expensive. Rare events need enormous sample counts, which is why variance-reduction ideas such as importance sampling exist.

Tradeoffs and failure modes

Monte Carlo is the right tool when the problem is high-dimensional or the integrand is too complicated to integrate by hand. It is the wrong tool when a smooth low-dimensional integral can be done more accurately by a deterministic rule.

SituationProblemBetter choice
One or two dimensions, smooth integrandMonte Carlo converges slowly compared with a gridQuadrature such as Simpson's rule or Gauss quadrature
Rare event with tiny probabilityAlmost no samples hit the event, so the relative error is huge[[importance-sampling
Cannot draw samples from pp directlyNo simple sampler exists[[markov-chain
Need an exact answerMonte Carlo gives an estimate with errorAnalytic methods, if they exist
Heavy-tailed f(X)f(X) with infinite varianceThe standard error formula breaks and the central limit theorem may not applyRobust estimators, or a different model

Practical failures are more common than theoretical ones. A poor random number generator can make the samples correlated, and then the effective sample size is smaller than nn. Samples from a Markov chain are correlated by construction, so the error bar from the formula above is too optimistic unless you correct for it. A small nn with a heavy-tailed ff often produces an error bar that looks tight and is wrong. The fix in all cases is to check the estimate with more samples, a different seed, or a second method before trusting it.

History

Buffon's needle (1777) is an early example of estimating π by random sampling, though it was not presented as a computational method. The modern method came out of work on the Manhattan Project. In the mid-1940s Stanislaw Ulam, working on neutron diffusion, realised that random simulation could handle problems that deterministic calculation could not. John von Neumann helped develop the approach on early computers at Los Alamos. Nicholas Metropolis suggested the name, and Metropolis and Ulam published the first description in 1949.

It caught on because electronic computers made each sample cheap, and the approach handles problems that resist every other technique. In 1953 Metropolis and colleagues introduced a sampling scheme for statistical mechanics that became the basis of Markov chain Monte Carlo, and it remains central to Bayesian statistics and machine learning.

Check yourself

QuestionWhat does the law of large numbers guarantee about μ^n\hat{\mu}_n as nn grows?Show answer

It converges to the true expected value μ\mu. Each extra sample pulls the average closer, so for large enough nn the estimate is as close to μ\mu as you like. The law of large numbers is what makes Monte Carlo consistent: the estimate is right in the limit.

QuestionYou draw x=0.1,0.4,0.9,0.6x = 0.1, 0.4, 0.9, 0.6 from a uniform distribution on [0,1][0, 1]. What is the Monte Carlo estimate of E[2X+1]\mathbb{E}[2X + 1]?Show answer

The mean of the samples is (0.1+0.4+0.9+0.6)/4=0.5(0.1 + 0.4 + 0.9 + 0.6)/4 = 0.5. By linearity, E[2X+1]=2 E[X]+1\mathbb{E}[2X + 1] = 2\,\mathbb{E}[X] + 1, so the estimate is 2×0.5+1=2.02 \times 0.5 + 1 = 2.0. You can also apply ff to each sample first: values are 1.2,1.8,2.8,2.21.2, 1.8, 2.8, 2.2, which average to 2.02.0.

QuestionWhy does the Monte Carlo error rate not depend on the dimension of XX?Show answer

The standard error is σf/n\sigma_f/\sqrt{n}, and nn is the only sample-size term. The dimension only enters through σf\sigma_f, which is the spread of f(X)f(X). A grid needs a number of points that grows exponentially with dimension, but random samples are evaluated the same way in any dimension, so the same nn gives the same 1/n1/\sqrt{n} rate.

QuestionA portfolio loses more than 10 million dollars with probability 10−610^{-6} per year. You simulate 10510^5 years with plain Monte Carlo. What is the chance you see no losses that large, and what should you do instead?Show answer

Each year misses with probability 1−10−61 - 10^{-6}, so the chance of no hits in 10510^5 independent years is (1−10−6)105≈e−0.1≈0.905(1 - 10^{-6})^{10^5} \approx e^{-0.1} \approx 0.905. You would most likely see zero events and an estimate of zero, with almost no information. Use importance sampling, which oversamples the tail and corrects the weights, or a model built for extreme values.

Sources