Settings

Theme
Lite Mode (saves mobile data)

In Lite Mode, animations and videos don't play until you tap them, and their size is shown first. Interactive widgets still work.

Text size

Back up or move your progress →

Part 1: Math FoundationsProbability and Statistics

Sampling and Monte Carlo

P1.D940 min●●○ IntermediateReviewed Dec 1, 2026

Why this matters for machine learning

Many quantities in ML are expectations or integrals with no formula, such as an expected loss, so they are estimated by averaging random samples, and generative models and language models produce their output by sampling.

  • The loss on a random mini-batch of BB examples is a Monte Carlo estimate of the loss over all the data, with error shrinking like 1/B1/\sqrt B. (P1.F4: Stochastic and mini-batch gradient descent, coming soon)
  • A language model writes text by drawing the next token from its softmax probabilities, with a table lookup in the cumulative sum. Temperature and top-kk reshape those probabilities before the draw. (P10.A5: Decoding strategies, coming soon)
  • Dropout draws a random mask of units to switch off at every step, and data augmentation draws a random crop or flip for every image. (P4.17: Regularization for neural nets, coming soon)
  • Test-set accuracy is an average over a random sample of test examples, so it carries the standard error p(1−p)/n\sqrt{p(1-p)/n} of this lesson. (P1.D8: Law of large numbers and the Central Limit Theorem)
  • Reinforcement learning estimates the value of a state, an expected return, by averaging the returns of sampled episodes; P9.3 explains what a value is. (P9.3: Value functions and the Bellman equation, coming soon)
  • A variational autoencoder draws a random latent code as μ+σz\mu+\sigma z with zz standard Gaussian, the recipe of this lesson, and diffusion models start from random noise. (P8.3: Variational Autoencoders, coming soon)

Before this: Probability basics, Random variables, Common distributions, Expectation and variance, Joint, marginal and conditional probability, Law of large numbers and the Central Limit Theorem

After this lesson you can

  • Estimate a probability as the fraction of random samples that hit an event, and an expectation E[f(X)]\mathbb{E}[f(X)] as the average of ff over samples, and give the standard error p(1−p)/n\sqrt{p(1-p)/n} or σf/n\sigma_f/\sqrt n, also estimated from the samples themselves
  • Use Monte Carlo integration, ∫abg(x) dx≈(b−a)⋅mean of g at uniform points\int_a^b g(x)\,dx\approx(b-a)\cdot\text{mean of }g\text{ at uniform points}, and say why the 1/n1/\sqrt n error does not depend on the dimension, where a grid costs mdm^d evaluations, and when a grid is still the better tool
  • Turn uniform random numbers into draws from other distributions: table lookup with a cumulative sum (discrete, as in a language model), the inverse CDF (exponential), Box–Muller (Gaussian) and rejection sampling, with its acceptance rate
  • Name the main pitfalls (rare events, correlated samples, heavy tails, a wasteful proposal in high dimension, unrecorded seeds) and compute how bad a rare-event estimate is

Throw darts at random onto a square board that has a quarter circle drawn in it. Count the darts that land inside the quarter circle. The share of darts inside is close to π/4\pi/4, so four times that share is close to π\pi: a number from geometry, found by throwing random darts. How good is the answer after 100100 darts, and after a million? And what does that have to do with training a neural network, or with a language model choosing its next word?

This is Monte Carlo: estimating a quantity by averaging random samples. Earlier lessons promised it. P1.D1 said that repeating a random experiment and counting is a way to estimate a probability. P1.D2 and P1.D3 said that other random draws are built from uniform ones. P1.C9 said that random points are how high-dimensional integrals are estimated. P1.D8 proved that averages settle and gave the error σ/n\sigma/\sqrt n. Here we use all of it.

Why sample at all?

Three kinds of quantity come up again and again:

  • a probability of a complicated event, such as “a model answers wrongly on a random input”;
  • an expectation E[f(X)]=∫f(x) p(x) dx\mathbb{E}[f(X)]=\int f(x)\,p(x)\,dx, such as the expected loss of a model over the whole distribution of inputs;
  • an integral or a volume, such as the area of a strange shape.

For most real problems none of these can be computed exactly. The sum has too many terms, the integral has no antiderivative (P1.C9), or the distribution of XX is only known as “a program that produces one draw”. But one draw is often cheap. Sampling means producing such draws, and Monte Carlo means averaging them. Every quantity above turns out to be an average in disguise.

Estimating a probability: darts and π

Throw a dart so that its position (x,y)(x,y) has both coordinates uniform on [0,1)[0,1) (P1.D3), independent of each other (P1.D5). The darts then land evenly over the unit square, which has area 11. The quarter circle x2+y2<1x^2+y^2\lt1 has area πr2/4=π/4≈0.7854\pi r^2/4=\pi/4\approx0.7854. For a uniform dart the probability of a region is its area, so

p=P(hit)=π4,soπ=4p.p=\mathbb{P}(\text{hit})=\frac{\pi}{4},\qquad\text{so}\qquad \pi=4p.

We do not know pp, but we can estimate it by throwing nn darts and counting the hits (darts inside the quarter circle). The estimate is p^=hits/n\hat p=\text{hits}/n, and the estimate of π\pi is 4 p^4\,\hat p. With 1010 darts and 77 hits, the estimate is 4×0.7=2.84\times0.7=2.8. Try it:

Darts at a square: estimating π

seed 541263
No darts thrown yet. Press one of the throw buttons.

The square

000.50.511x

hit: inside the quarter circle, x² + y² < 1 miss: outside

Running estimate of π against the number of darts

01234110number of darts n (log scale)

running estimate 4 × hits / n π = 3.1416 π ± 1.96 sd, where about 95% of runs should fall

darts thrown n = 0 hits = 0 estimate 4 × hits / n = — error, estimate − π = — band half-width 1.96 sd = — inside the band? — standard error from the data, 4√(p̂(1 − p̂)/n) with p̂ = hits/n: —
Darts at a square. Each dart lands at a uniform random point of the unit square. A dart inside the quarter circle is a hit (a blue dot); one outside is a miss (a pink cross). The chart shows the running estimate 4 × hits / n against the number of darts n on a log axis, with a shaded band that is π ± 1.96 standard deviations of the estimate. Throw 1, 10, 100, 1000 or 10,000 darts at a time. New seed starts a different run, and Restart with the same seed replays the same darts. Zoom in on π to see the late part of the run. The widget stops at 100,000 darts.

Things to try. Throw darts one at a time and note that the estimate can only be 00 or 44 after the first dart. Throw 100100, then 10001000, then 10,00010{,}000, and watch the line leave the wide early swings and creep toward π\pi. Press New seed and run again: the path is different, but it ends in the same place. Press Restart with the same seed and the same darts come back, so the same path.

How big is the error?

Each dart is a hit with probability pp and a miss otherwise, so the number of hits is binomial (P1.D3) and p^\hat p is an average of nn zeros and ones. P1.D8 gave its spread: the standard deviation of p^\hat p is p(1−p)/n\sqrt{p(1-p)/n}. The estimate of π\pi is 4p^4\hat p, so its standard deviation is four times that:

sd(4p^)=4p(1−p)n=1.642n.\mathrm{sd}(4\hat p)=4\sqrt{\frac{p(1-p)}{n}}=\frac{1.642}{\sqrt n}.

The last step puts in p=π/4p=\pi/4.

darts nnsd(p^)\mathrm{sd}(\hat p)sd of the estimate of π\piband ±1.96 sd\pm1.96\,\mathrm{sd}
10100.1300.1300.5190.519±1.018\pm1.018
1001000.04100.04100.1640.164±0.322\pm0.322
100010000.01300.01300.05190.0519±0.102\pm0.102
10410^40.004110.004110.01640.0164±0.0322\pm0.0322
10610^60.0004110.0004110.001640.00164±0.00322\pm0.00322

By the central limit theorem (P1.D8) the estimate is roughly Gaussian for large nn, so for large nn it lands inside the band in about 95%95\% of runs. That is the shaded band in the widget. Two lessons sit in the table. First, ten times more precision costs a hundred times more darts: from n=100n=100 to n=104n=10^4, a hundred times the darts, the standard deviation falls from 0.1640.164 to 0.01640.0164, only ten times. Second, throwing darts is a poor way to compute π\pi. To be within ±0.001\pm0.001 with 95%95\% confidence you need n=(1.96×1.642/0.001)2≈107n=(1.96\times1.642/0.001)^2\approx10^7 darts.

One honest detail. The band above uses the true p=π/4p=\pi/4, which a real experiment does not know. In practice you plug in the data: p^=hits/n\hat p=\text{hits}/n gives the standard error from the data, 4p^(1−p^)/n4\sqrt{\hat p(1-\hat p)/n}, shown in the last readout of the widget. It is close to the formula for any nn that is not tiny.

Estimating an expectation

Now the general rule. Let XX be a random variable with density (or PMF) pp, and ff any function. To estimate E[f(X)]\mathbb{E}[f(X)], draw x1,…,xnx_1,\dots,x_n independently from pp and average:

E[f(X)]≈μ^n=1n∑i=1nf(xi).\mathbb{E}[f(X)]\approx\hat\mu_n=\frac1n\sum_{i=1}^n f(x_i).

A probability is the special case f=f= an indicator: P(X∈A)=E[1A(X)]\mathbb{P}(X\in A)=\mathbb{E}[\mathbf 1_A(X)], and the average of the indicator is the fraction of hits. That is the darts. The estimate has three properties, all from P1.D4 and P1.D8:

  • It is unbiased: E[μ^n]=1n∑E[f(X)]=E[f(X)]\mathbb{E}[\hat\mu_n]=\frac1n\sum\mathbb{E}[f(X)]=\mathbb{E}[f(X)], so its average over many repeats is the true value.
  • It is consistent: by the law of large numbers it settles on E[f(X)]\mathbb{E}[f(X)] as nn grows.
  • Its standard error is σf/n\sigma_f/\sqrt n, where σf\sigma_f is the standard deviation of f(X)f(X) (finite, and the draws independent). The CLT says μ^n\hat\mu_n is roughly Gaussian, so μ^n±1.96 σf/n\hat\mu_n\pm1.96\,\sigma_f/\sqrt n is a rough 95%95\% interval.

We do not know σf\sigma_f either, but the samples give it: compute ss, the sample standard deviation of the numbers f(xi)f(x_i) (with n−1n-1 in the denominator), and report s/ns/\sqrt n. An estimate without its standard error is half an answer.

Small example with a known answer. Let XX be uniform on [0,1][0,1] and f(x)=x2f(x)=x^2. Then E[f(X)]=∫01x2dx=13\mathbb{E}[f(X)]=\int_0^1x^2dx=\frac13, and σf=15−19=4/45=0.298\sigma_f=\sqrt{\frac15-\frac19}=\sqrt{4/45}=0.298. With n=100n=100 samples the standard error is 0.298/10=0.0300.298/10=0.030, so the estimate is typically within a few hundredths of 0.3330.333. With n=104n=10^4 it is 0.00300.0030.

Monte Carlo integration

An integral is an expectation. If UU is uniform on [a,b][a,b], its density is 1b−a\frac1{b-a}, so

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

so that

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

and replacing the expectation by an average over uniform points u1,…,unu_1,\dots,u_n gives

∫abg(x) dx≈b−an∑i=1ng(ui).\int_a^b g(x)\,dx\approx\frac{b-a}{n}\sum_{i=1}^n g(u_i).

In words: the integral is the length of the interval times the average height of the function, and we measure the average height at random points. P1.C9 added up thin strips at evenly spaced points (a Riemann sum). Monte Carlo evaluates the function at random points instead. A region of area AA inside a box of area VV works the same way, with gg the indicator of the region: A≈V⋅hits/nA\approx V\cdot\text{hits}/n. That is the darts again, with V=1V=1.

Example with an exact answer: ∫0πsin⁡x dx=2\int_0^\pi\sin x\,dx=2 (P1.C9). Here g(U)=sin⁡Ug(U)=\sin U has E[sin⁡2U]=12\mathbb{E}[\sin^2U]=\frac12 and mean 2/π2/\pi, so σg=12−4π2=0.308\sigma_g=\sqrt{\frac12-\frac4{\pi^2}}=0.308, and the estimate π⋅sin⁡ui‾\pi\cdot\overline{\sin u_i} has standard error π×0.308/n=0.967/n\pi\times0.308/\sqrt n=0.967/\sqrt n. At n=1000n=1000 that is 0.0310.031. The code cell below does it: one seeded run gives 1.989±0.0301.989\pm0.030. The error was 0.0110.011, about a third of the standard error, which is ordinary.

Notice what the cell also shows. In one dimension the midpoint rule with the same 10001000 function values gives 2.00000082.0000008, which is off by less than 10−610^{-6}. For a smooth function of one variable, evenly spaced points are far better than random ones. Monte Carlo earns its place only when there are many variables.

The error rate does not depend on the dimension

A grid with mm points per axis has mdm^d points in dd dimensions. With m=10m=10 that is 100100 evaluations for d=2d=2, 101010^{10} for d=10d=10, and 102010^{20} for d=20d=20, which is out of reach. Monte Carlo spends exactly nn evaluations, whatever dd is, and its standard error is still σf/n\sigma_f/\sqrt n. The dimension enters only through σf\sigma_f.

Take f(x)=x12+⋯+xd2f(\mathbf x)=x_1^2+\dots+x_d^2 for x\mathbf x uniform in the cube [0,1]d[0,1]^d. Its mean is d/3d/3 and σf=4d/45\sigma_f=\sqrt{4d/45} (the dd terms are independent, each with variance 445\frac4{45}). With n=104n=10^4 samples:

dimension ddexact mean d/3d/3σf\sigma_fstandard error (relative)
110.3330.3330.2980.2980.00300.0030 (0.89%0.89\%)
10103.3333.3330.9430.9430.00940.0094 (0.28%0.28\%)
10010033.3333.332.9812.9810.0300.030 (0.089%0.089\%)

A grid with 1010 points per axis would need 1010, 101010^{10} and 1010010^{100} evaluations for these three rows. Ten thousand random points give a good estimate in a hundred dimensions, where the grid is hopeless. The relative error shrinks down the table only because the mean of this ff grows like dd while σf\sigma_f grows like d\sqrt d; other functions behave differently.

Be honest about three limits. (1) σf\sigma_f can itself grow with the dimension for a badly behaved ff, and then Monte Carlo is no cure. (2) In one to three dimensions a grid beats random points for smooth functions: the midpoint rule’s error with N=mdN=m^d points shrinks like N−2/dN^{-2/d}, which is faster than N−1/2N^{-1/2} when d<4d\lt4 and slower when d>4d\gt4. (3) Monte Carlo needs a way to draw from the distribution pp, which is the next topic.

Where random numbers come from

A computer is deterministic, so it cannot throw dice. A pseudo-random number generator (PRNG) is a formula that, from a starting number called the seed, produces a long sequence that behaves like independent random numbers. Start from the same seed and you get the same sequence. NumPy’s default_rng(0) gives 0.637,0.270,0.041,…0.637, 0.270, 0.041,\dots every time. Start from a new seed and you get a different one.

The basic output is a number uniform on [0,1)[0,1): every stretch of the same length is equally likely, with density 11 (P1.D3). Everything else is built from it, and the browser simulators in P1.D1 and in this lesson use a small seeded generator.

Why this matters. A seed makes a run reproducible: record it and anyone can replay your experiment, which is why the widget above shows its seed. It does not make the numbers less random in a statistical sense. Two warnings: do not choose the seed that gives the answer you like, and the same seed is only guaranteed to reproduce the same numbers with the same library version. P1.G3 covers generators, seeding and why GPU runs can differ.

Sampling from other distributions

We now have uniform numbers. Four tools turn them into draws from other distributions.

Discrete: table lookup in the cumulative sum

Suppose a variable takes the values 0,1,20,1,2 with probabilities 0.5,0.3,0.20.5,0.3,0.2. Lay the probabilities end to end on [0,1)[0,1): the stretch [0,0.5)[0,0.5) belongs to value 00, [0.5,0.8)[0.5,0.8) to value 11, and [0.8,1)[0.8,1) to value 22. The cumulative sums 0.5,0.8,1.00.5,0.8,1.0 are the right ends of the stretches. Draw uu uniform on [0,1)[0,1) and return the first value whose cumulative sum is above uu. For u=0.62u=0.62 the answer is value 11. Each value is returned with probability equal to the length of its stretch, which is its probability.

A language model does exactly this. For logits (2,1,0)(2,1,0) the softmax (P3.A8) gives probabilities (0.665,0.245,0.090)(0.665,0.245,0.090) and cumulative sums (0.665,0.910,1)(0.665,0.910,1). A draw u=0.7u=0.7 returns the second token. Always taking the largest probability (greedy decoding) would always return the first, while sampling returns the first about 66.5%66.5\% of the time. Temperature TT divides the logits before the softmax: for T=0.5T=0.5 the probabilities become (0.867,0.117,0.016)(0.867,0.117,0.016), sharper, and for T=2T=2 they become (0.506,0.307,0.186)(0.506,0.307,0.186), flatter. Top-kk keeps only the kk largest probabilities and renormalizes. In all cases the draw is the same table lookup (P10.A5).

Continuous: the inverse CDF

P1.D2 showed that if FF is a strictly increasing continuous CDF and UU is uniform on [0,1)[0,1), then X=F−1(U)X=F^{-1}(U) has CDF FF. The proof is one line: P(X≤x)=P(U≤F(x))=F(x)\mathbb{P}(X\le x)=\mathbb{P}(U\le F(x))=F(x). For the exponential with rate λ\lambda, F(x)=1−e−λxF(x)=1-e^{-\lambda x}. Solving u=F(x)u=F(x) gives

x=F−1(u)=−ln⁡(1−u)λ.x=F^{-1}(u)=-\frac{\ln(1-u)}{\lambda}.

For λ=2\lambda=2 and u=0.5u=0.5 this is ln⁡2/2=0.347\ln2/2=0.347, the median; for u=0.9u=0.9 it is 1.1511.151. Because 1−U1-U is uniform too, −ln⁡(U)/λ-\ln(U)/\lambda works as well (for U>0U\gt0). Move uu in the widget and read xx off the curve. Then draw many: equal steps of uu land on the curve at xx values that crowd together where the CDF is steep, which is where the density is high.

Inverse-CDF sampling: the exponential

With u = 0.5 and rate λ = 1, the formula gives x = −ln(1 − 0.5) / 1 = 0.693. Going back, F(0.693) = 1 − e^(−1 × 0.693) = 0.5, which is u.

The CDF F(x) and its inverse

00.250.50.751012345x

the chosen u on the vertical axis its x on the horizontal axis

The drawn numbers against the exponential density

00.51012345x

share of the drawn numbers per unit of x density λ e−λx

u = 0.5 x = −ln(1 − u)/λ = 0.693 numbers drawn = 0 their average = — (1/λ = 1)
Inverse-CDF sampling for the exponential distribution. The blue curve is the CDF F(x). The pink dot is the chosen uniform number u on the vertical axis; the dashed line goes across to the curve and down to the blue square, the number x = −ln(1 − u)/λ. Draw 10 or 1000 random u values: the histogram of the resulting x values follows the density λe^(−λx) (pink curve). Changing the rate λ clears the drawn numbers. The widget keeps at most 10,000 drawn numbers.

Gaussian: Box–Muller, or the library

The Gaussian CDF has no formula and so no formula for F−1F^{-1} (P1.D2). In practice call the library (rng.normal(mu, sigma)). One classical recipe is Box–Muller: take two independent uniform numbers u1∈(0,1]u_1\in(0,1] and u2∈[0,1)u_2\in[0,1), and set

z1=−2ln⁡u1 cos⁡(2πu2),z_1=\sqrt{-2\ln u_1}\,\cos(2\pi u_2), z2=−2ln⁡u1 sin⁡(2πu2).z_2=\sqrt{-2\ln u_1}\,\sin(2\pi u_2).

Then z1z_1 and z2z_2 are independent standard Gaussians. For u1=0.3u_1=0.3 and u2=0.25u_2=0.25 they are 00 and 1.5521.552. To get N(μ,σ2)N(\mu,\sigma^2), use x=μ+σzx=\mu+\sigma z, which is the recipe a variational autoencoder uses for its latent code (P8.3).

Rejection sampling

Sometimes you can evaluate the density p(x)p(x) but cannot invert its CDF. Rejection sampling needs only a ceiling cc with p(x)≤cp(x)\le c on an interval. Throw a dart at the rectangle: xx uniform on the interval and yy uniform on [0,c][0,c]. Keep xx if the dart is under the curve (y≤p(x)y\le p(x)), otherwise throw it away and try again. The kept xx values have density pp: at each xx, the dart lands under the curve with a chance proportional to p(x)p(x). The acceptance rate is the area under the curve divided by the area of the rectangle, 1/(c×width)1/(c\times\text{width}) for a density.

Example: the density p(x)=6x(1−x)p(x)=6x(1-x) on [0,1][0,1] has its largest value 1.51.5 at x=12x=\frac12, so use c=1.5c=1.5. The acceptance rate is 11.5=23\frac1{1.5}=\frac23, so on average 1.51.5 proposals per kept sample. The kept samples have mean 0.50.5 and P(X≤0.25)=0.156\mathbb{P}(X\le0.25)=0.156, as the third code cell checks.

The darts are rejection sampling. Draw points uniformly in the square and keep those inside the quarter circle: the kept ones are uniform on the quarter circle, and the acceptance rate is π/4=0.785\pi/4=0.785. In dd dimensions the same idea, a ball inside the cube around it, has acceptance rate Vd/2dV_d/2^d, where VdV_d is the volume of the unit ball: 0.7850.785 at d=2d=2, 0.5240.524 at d=3d=3, 0.1640.164 at d=5d=5, 0.00250.0025 at d=10d=10, and 2.5×10−82.5\times10^{-8} at d=20d=20. A poor ceiling or a high dimension makes rejection hopeless.

Go deeper When you cannot sample from the distribution directly: importance sampling and MCMC

Importance sampling draws from an easier distribution qq and corrects with weights: Ep[f(X)]=Eq ⁣[f(X) p(X)q(X)]\mathbb{E}_p[f(X)]=\mathbb{E}_q\!\left[f(X)\,\frac{p(X)}{q(X)}\right], valid when qq is positive wherever f pf\,p is not zero. The average of f(xi) p(xi)/q(xi)f(x_i)\,p(x_i)/q(x_i) over draws xi∼qx_i\sim q is an unbiased estimate. It shines for rare events. Take the standard Gaussian chance P(Z>4)=3.17×10−5\mathbb{P}(Z\gt4)=3.17\times10^{-5}. Plain sampling with 10610^6 draws sees about 3232 hits, a relative error of 0.180.18. Sampling instead from N(4,1)N(4,1), where the event is common, with weights e8−4xe^{8-4x}, gives a relative standard error of 0.0210.021 with only 10410^4 draws; plain sampling with 10410^4 draws would expect only 0.30.3 hits. A poor qq can make the variance infinite, so qq needs tails at least as heavy as pp where it counts.

Markov chain Monte Carlo (MCMC) is for the case where pp is known only up to a constant (as in Bayesian posteriors). It builds a chain of dependent samples whose long-run distribution is pp. Because consecutive samples are correlated, they count for fewer than nn independent ones (see the pitfalls below).

With or without replacement, and shuffling

Drawing with replacement makes the draws independent, so every formula above applies. Drawing without replacement from a finite population of NN items makes them slightly dependent: after you draw one, it cannot appear again. The variance of the sample mean becomes σ2n⋅N−nN−1\frac{\sigma^2}{n}\cdot\frac{N-n}{N-1}, where σ2\sigma^2 is the population variance. It is smaller, so the with-replacement formula is a little pessimistic: the factor is 0.5050.505 for n=50n=50 of N=100N=100, and 0.9010.901 for n=100n=100 of N=1000N=1000. When nn is tiny compared with NN, the difference vanishes.

To shuffle is to put the items in a uniformly random order (a random permutation). Shuffling the training set and cutting it into mini-batches draws batches without replacement within an epoch (P1.F4). The factor above shows that the σ/B\sigma/\sqrt B formula is then a good, slightly pessimistic, approximation while BB is small compared with the data set.

Go deeper The bootstrap: resampling your own data

You have one data set of NN examples and want to know how much an estimate (an average, an accuracy) would vary on a fresh data set, which you cannot collect. The bootstrap draws NN examples with replacement from your data, recomputes the estimate, and repeats many times. The spread of the recomputed values stands in for the real sampling spread. One fact: each resample leaves out about 1/e=36.8%1/e=36.8\% of the examples, because the chance that a given example is never drawn in NN tries is (1−1/N)N(1-1/N)^N, which is 0.3660.366 for N=100N=100 and tends to e−1e^{-1}. Bagging (P3.B4) trains each model of an ensemble on one bootstrap sample.

When Monte Carlo goes wrong

Rare events. To estimate a probability pp from nn samples, the standard error is p(1−p)/n\sqrt{p(1-p)/n}, which is small in absolute terms for small pp. What matters is the relative error, the standard error divided by pp:

p(1−p)/np=1−pnp≈1np.\frac{\sqrt{p(1-p)/n}}{p}=\sqrt{\frac{1-p}{np}}\approx\frac1{\sqrt{np}}.

It depends on the expected number of hits, npnp. With p=10−3p=10^{-3} and n=104n=10^4 you expect 1010 hits and the relative error is 0.320.32. With p=10−6p=10^{-6} and n=106n=10^6 you expect one hit, the relative error is about 11, and the chance of no hit at all is (1−10−6)106≈e−1=0.37(1-10^{-6})^{10^6}\approx e^{-1}=0.37. To get 10%10\% at p=10−6p=10^{-6} you need about 10810^8 samples. A nasty trap: with zero hits the estimate is p^=0\hat p=0 and the formula p^(1−p^)/n\sqrt{\hat p(1-\hat p)/n} also says 00, a confident but wrong answer. Rare failures of a very reliable model are hard to measure for this reason.

Correlated samples. The error σf/n\sigma_f/\sqrt n assumes independent draws. If each sample resembles the previous one, as in MCMC or in a simulation that reuses its state, the samples carry less information than nn. Reusing one seed for several “independent” runs gives identical, not independent, runs.

Go deeper Correlated samples and the effective sample size

Suppose the samples form a sequence in which neighbouring values have correlation ρ\rho and the correlation fades geometrically (an AR(1) process). For a long run the variance of the average is about σ2n⋅1+ρ1−ρ\frac{\sigma^2}{n}\cdot\frac{1+\rho}{1-\rho}, so the run is worth only neff=n 1−ρ1+ρn_\text{eff}=n\,\frac{1-\rho}{1+\rho} independent samples. For ρ=0.9\rho=0.9 the factor is 0.11.9=0.0526\frac{0.1}{1.9}=0.0526: 10001000 correlated samples are worth about 5353 independent ones, and the true standard error is 19=4.4\sqrt{19}=4.4 times the naive σ/n\sigma/\sqrt n. A simulation of this chain (4000 repeats of 1000 steps) measured an average with standard deviation 0.1370.137, against 0.03160.0316 from the naive formula and 0.1380.138 from the one above.

Heavy tails. The standard error needs a finite variance. For a population like the Cauchy (P1.D8) the standard error is not defined and the average never settles.

Slow progress. The 1/n1/\sqrt n rate is slow: a thousand times fewer errors costs a million times more samples. Methods that reduce σf\sigma_f itself (variance reduction) exist, but this lesson does not cover them.

Where this shows up in machine learning

The expected loss over a data distribution is E[L]=∫L(x)p(x) dx\mathbb{E}[L]=\int L(x)p(x)\,dx. Sampling and averaging appear in many places:

  • Mini-batches. A mini-batch of BB examples drawn from the data gives 1B∑L(xi)\frac1B\sum L(x_i), a Monte Carlo estimate with standard error σL/B\sigma_L/\sqrt B, which is why batch size trades noise for cost (P1.D8, P1.F4).
  • Test sets. A test set is another sample: its accuracy has standard error p(1−p)/n\sqrt{p(1-p)/n} (P1.D8).
  • Randomness inside training. Dropout draws a fresh random mask at every step (P4.17), data augmentation draws a random transformation of each image (P4.18), random initialization draws weights from a uniform or Gaussian distribution (P4.12), and random hyperparameter search draws settings from ranges (P4.23).
  • Generation. A language model samples its next token (P10.A5), and a variational autoencoder samples its latent code (P8.3).
  • Reinforcement learning. An agent can estimate the value of a state by averaging returns from sampled episodes; P9.3 explains what a value is.

Each case is a draw from a distribution, or an average over such draws, and the rules above say how much to trust it.

Intuition

Monte Carlo is a poll. To learn what a huge population thinks you do not ask everyone; you ask a random sample and report the share, with a margin of error that depends on the sample size, not on how large the population is. A function averaged over a huge space is answered the same way: sample it at random points and average. The analogy breaks in two places: a poll can fail by bias in how people are picked, while a program draws from the distribution it is given; and a pollster cannot ask the same person a thousand times, while a program can call the function as often as it likes.

Math

Estimator. For i.i.d. xi∼px_i\sim p, μ^n=1n∑f(xi)\hat\mu_n=\frac1n\sum f(x_i) has E[μ^n]=E[f(X)]\mathbb{E}[\hat\mu_n]=\mathbb{E}[f(X)] and Var(μ^n)=σf2/n\mathrm{Var}(\hat\mu_n)=\sigma_f^2/n, so the standard error is σf/n\sigma_f/\sqrt n. The sample variance s2=1n−1∑(f(xi)−μ^n)2s^2=\frac1{n-1}\sum(f(x_i)-\hat\mu_n)^2 is an unbiased estimate of σf2\sigma_f^2.

Probability. With f=1Af=\mathbf 1_A, σf2=p(1−p)\sigma_f^2=p(1-p), so the standard error is p(1−p)/n\sqrt{p(1-p)/n} and the relative error is (1−p)/(np)\sqrt{(1-p)/(np)}. For the darts, p=π/4p=\pi/4 and sd(4p^)=4p(1−p)/n=1.642/n\mathrm{sd}(4\hat p)=4\sqrt{p(1-p)/n}=1.642/\sqrt n.

Integral. ∫abg=(b−a) E[g(U)]\int_a^bg=(b-a)\,\mathbb{E}[g(U)] for U∼Uniform(a,b)U\sim\mathrm{Uniform}(a,b). The estimate (b−a)gˉ(b-a)\bar g has standard error (b−a) σg/n(b-a)\,\sigma_g/\sqrt n.

Inverse CDF. P(F−1(U)≤x)=P(U≤F(x))=F(x)\mathbb{P}(F^{-1}(U)\le x)=\mathbb{P}(U\le F(x))=F(x). For the exponential, u=1−e−λx⇒x=−ln⁡(1−u)/λu=1-e^{-\lambda x}\Rightarrow x=-\ln(1-u)/\lambda.

Rejection. With a proposal x∼Uniformx\sim\mathrm{Uniform} on an interval of width ww and y∼Uniform(0,c)y\sim\mathrm{Uniform}(0,c), a point is accepted with probability p(x)/cp(x)/c given xx. Overall acceptance is ∫p/(cw)=1/(cw)\int p/(cw)=1/(cw), and the accepted xx have density ∝p(x)\propto p(x), which is pp itself.

Box–Muller. R2=−2ln⁡u1R^2=-2\ln u_1 is exponential with rate 12\frac12 and the angle 2πu22\pi u_2 is uniform and independent. A pair of independent standard Gaussians has exactly this radius and angle distribution, because its joint density 12πe−(z12+z22)/2\frac1{2\pi}e^{-(z_1^2+z_2^2)/2} depends only on the radius.

Code

Categorical sampling and the exponential inverse CDF in NumPy. np.searchsorted(cum, u, side="right") returns the index of the first cumulative value above uu.

import numpy as np

rng = np.random.default_rng(0)
cum = np.cumsum([0.5, 0.3, 0.2])
u = rng.random(100_000)
print(np.bincount(np.searchsorted(cum, u, side="right")) / len(u))   # near 0.5, 0.3, 0.2

x = -np.log(1 - rng.random(100_000)) / 2.0                            # exponential, rate 2
print(x.mean())                                                       # near 1/2
print(rng.choice(3, size=5, p=[0.5, 0.3, 0.2]))                       # the library does the lookup for you

Try it: Monte Carlo in code

The first cell throws darts with a fixed seed for n=10n=10 up to 10610^6 and prints the estimate, the error and the band. It then repeats the 10001000-dart experiment 20002000 times and checks the share of runs inside the band and the spread of the estimates against the formula. The second cell estimates ∫0πsin⁡x dx\int_0^\pi\sin x\,dx and compares it with the midpoint rule, then runs the dimension example. The third cell tests the sampling tools: the cumulative-sum lookup, the exponential, Box–Muller, rejection and a rare event.

Try it: estimating π with darts

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

With seed 00 the cell prints 77 hits for 1010 darts (estimate 2.82.8), 822822 hits for 10001000 darts (estimate 3.2883.288, error +0.146+0.146, outside the band, which happens in about one run in twenty) and 785,259785{,}259 hits for 10610^6 darts (estimate 3.14103.1410, error −0.0006-0.0006). The share of 20002000 repeated runs inside the band is 0.95750.9575, near 0.950.95, and the spread of the estimates is 0.05120.0512 against the formula 0.05190.0519.

Try it: Monte Carlo integration and the dimension

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

The first line gives 1.9893±0.03031.9893\pm0.0303 against the exact 22 (the theoretical standard deviation is 0.03060.0306). In the second part the standard errors 0.00300.0030, 0.00950.0095 and 0.02980.0298 match σf/100\sigma_f/100 from the table above, even in 100100 dimensions. Challenge: change nn to 100,000100{,}000 and check that the standard error drops by a factor of 1010.

Try it: the sampling toolbox

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

Each printed estimate sits close to its exact value: the cumulative-sum lookup returns 0.665,0.245,0.0900.665, 0.245, 0.090 of the time, the exponential has mean 0.50.5 and 0.6310.631 of its mass below 0.50.5 (exact 0.6320.632), Box–Muller gives standard deviation 1.0021.002 and uncorrelated pairs, rejection accepts 0.6670.667 of the points, and the rare event shows a measured relative error of 0.3230.323 against the formula 0.3160.316. The last line is the 0.3680.368 chance of seeing no hit at all.

Common mistakes

Check your understanding

  1. You want the average of a function over a cube in d=20d=20 dimensions. A grid with 1010 points per axis, or 10,00010{,}000 independent random points? Which statement is correct?

  2. A Monte Carlo estimate has a standard error of 0.040.04 with n=1000n=1000 samples. About how many samples give a standard error of 0.0040.004?

  3. To sample from the exponential distribution with rate λ=2\lambda=2 using the inverse CDF, you draw u=0.9u=0.9. Which value of xx do you return?

  4. You use rejection sampling for the density p(x)=6x(1−x)p(x)=6x(1-x) on [0,1][0,1], with xx uniform on [0,1][0,1] and a ceiling c=1.5c=1.5. What fraction of the proposed points is accepted?

  5. A rare event has probability p=10−6p=10^{-6}. You draw 10610^6 independent samples and count the hits. About how likely is it that you see no hit at all?

Exercises

  1. A run of 10001000 darts gives 800800 hits. Give the estimate of π\pi, its error, and the standard error computed from the data.
    Show answerThe estimate is 4×0.8=3.24\times0.8=3.2, which is 0.0580.058 above π\pi. The data give p^=0.8\hat p=0.8 and standard error 40.8×0.2/1000=0.05064\sqrt{0.8\times0.2/1000}=0.0506, so the error is about 1.151.15 standard errors, an ordinary size.
  2. How many darts make the estimate of π\pi lie within ±0.01\pm0.01 with about 95%95\% probability?
    Show answern=(1.96×1.642/0.01)2≈103,600n=(1.96\times1.642/0.01)^2\approx103{,}600. For ±0.001\pm0.001 it is a hundred times more, about 10710^7.
  3. Use the four uniform points 0.2,0.7,1.5,1.90.2,0.7,1.5,1.9 on [0,2][0,2] to estimate ∫02x2dx\int_0^2x^2dx, and compare with the exact value.
    Show answerThe values of gg are 0.04,0.49,2.25,3.610.04,0.49,2.25,3.61, with mean 1.59751.5975. Times the length 22: 3.1953.195. The exact value is 8/3=2.6678/3=2.667. Four points give a rough answer, with a large error.
  4. A variable takes values 0,1,20,1,2 with probabilities 0.2,0.5,0.30.2,0.5,0.3. Which value does each draw return: u=0.1u=0.1, u=0.65u=0.65, u=0.95u=0.95?
    Show answerThe cumulative sums are 0.2,0.7,10.2,0.7,1. So u=0.1u=0.1 returns 00, u=0.65u=0.65 returns 11, and u=0.95u=0.95 returns 22.
  5. Sample from the exponential with rate λ=0.5\lambda=0.5 using u=0.75u=0.75. What is the mean of this distribution?
    Show answerx=−ln⁡(0.25)/0.5=2.77x=-\ln(0.25)/0.5=2.77. The mean is 1/λ=21/\lambda=2.
  6. The density p(x)=2xp(x)=2x on [0,1][0,1] is sampled by rejection with a uniform proposal. What ceiling and acceptance rate result? Is there a cheaper way?
    Show answerThe largest value is 22 at x=1x=1, so c=2c=2 and the acceptance rate is 12\frac12: two proposals per kept sample on average. The inverse CDF is cheaper: F(x)=x2F(x)=x^2, so x=ux=\sqrt u needs one uniform number per sample and rejects nothing.
  7. You estimate a probability p=0.001p=0.001 and want a relative error of 10%10\%. How many samples?
    Show answer(1−p)/(np)=0.1\sqrt{(1-p)/(np)}=0.1 gives n=(1−p)/(0.01 p)=0.999/(10−5)≈99,900n=(1-p)/(0.01\,p)=0.999/(10^{-5})\approx99{,}900, about 10510^5 samples, which means about 100100 expected hits.
  8. Out of 100100 samples, no hit occurs. What does the standard error from the data say, and why is it misleading?
    Show answerWith p^=0\hat p=0 it says 00. But a true p=0.03p=0.03 gives no hit in 100100 samples with probability 0.97100≈0.0480.97^{100}\approx0.048, about one time in twenty. Zero hits only says that pp is probably below a few percent, not that it is zero.
  9. A sample of n=50n=50 is drawn without replacement from a population of N=200N=200. By what factor is the variance of the mean smaller than the with-replacement value, and the standard deviation?
    Show answerThe factor is N−nN−1=150199=0.754\frac{N-n}{N-1}=\frac{150}{199}=0.754 for the variance, and its square root 0.8680.868 for the standard deviation.
  10. Apply Box–Muller with u1=0.5u_1=0.5 and u2=0u_2=0, then turn z1z_1 into a draw from N(10,22)N(10,2^2).
    Show answerz1=−2ln⁡0.5cos⁡0=1.386=1.177z_1=\sqrt{-2\ln0.5}\cos0=\sqrt{1.386}=1.177 and z2=1.386sin⁡0=0z_2=\sqrt{1.386}\sin0=0. The draw is μ+σz1=10+2×1.177=12.35\mu+\sigma z_1=10+2\times1.177=12.35.
  11. You report a Monte Carlo result of 0.520.52 from a run with seed 77, and your colleague gets 0.490.49 with seed 88. Is something wrong? What should you do?
    Show answerNot necessarily: different seeds give different estimates, scattered by about the standard error. Compare the difference with the standard errors. Record the seeds, and report the estimate with its standard error, or the mean and spread over several seeds.
  12. Why does a heavy-tailed function make the standard error unreliable even when nn is large?
    Show answerThe formula σf/n\sigma_f/\sqrt n needs a finite variance. With very heavy tails the sample standard deviation ss is dominated by a few huge draws, can keep growing with nn, and the average itself may not settle (the Cauchy case of P1.D8).

Next: P1.D10 asks the reverse question: given data, which parameters make them most probable (maximum likelihood). P1.G3 explains pseudo-random generators and seeds in depth, P1.F4 uses random mini-batches as Monte Carlo estimates of the gradient, and P10.A5 shows temperature and top-kk sampling of the next token.

Key takeaways

  • Monte Carlo means estimating a quantity by averaging random samples. A probability is a fraction of hits, and an expectation is E[f(X)]≈1n∑if(xi)\mathbb{E}[f(X)]\approx\frac1n\sum_i f(x_i) for independent draws xix_i. The estimate is unbiased: its average over many repeats is the true value.
  • The standard error is σf/n\sigma_f/\sqrt n, or p(1−p)/n\sqrt{p(1-p)/n} for a probability, from the law of large numbers and the CLT (P1.D8). Ten times more precision costs a hundred times more samples. With independent samples and a finite variance, this rate does not depend on the dimension.
  • Darts at a square: the share of darts inside the quarter circle is π/4\pi/4, so 4⋅hits/n4\cdot\text{hits}/n estimates π\pi, with standard deviation 1.642/n1.642/\sqrt n. About 10710^7 darts give ±0.001\pm0.001 at 95%95\%, so this is a way to learn Monte Carlo, not to compute π\pi.
  • Integration: ∫abg(x) dx≈(b−a)⋅mean of g(ui)\int_a^b g(x)\,dx\approx(b-a)\cdot\text{mean of }g(u_i) for uniform points uiu_i. A grid with mm points per axis needs mdm^d evaluations, so random points win in high dimension. In one to three dimensions a grid is usually more accurate for a smooth function.
  • Computers make pseudo-random numbers from a seed: the same seed gives the same sequence. Everything starts from Uniform[0,1)[0,1). A discrete draw is a table lookup in the cumulative sum. A continuous draw can use the inverse CDF, for example x=−ln⁡(1−u)/λx=-\ln(1-u)/\lambda. A Gaussian can come from Box–Muller or a library. Rejection sampling keeps the points under a curve and has acceptance rate area divided by box area.
  • Pitfalls: a rare event with probability pp has relative error (1−p)/(np)\sqrt{(1-p)/(np)}, so p=10−6p=10^{-6} needs about 10810^8 samples for 10%10\%. Correlated samples count for fewer than nn. Rejection in high dimension accepts almost nothing. Record the seed, and report the standard error with every estimate.
Found a mistake? Tell us