Monte Carlo Simulation

Throw random darts and count: you get π, an option price or the colour of a pixel. The error shrinks like 1 over the square root of N, so 100 times the darts buys 10 times the accuracy.

Pick how many darts to throw. The board runs the same experiment 20 times, and each run lands as one warm dot. Watch the dots close in on π as N grows. Then we build, piece by piece, the estimator, its error bar, the law that sets its cost, and the tricks that cut that cost.

You need an average, a probability and a little Python. We build the rest from zero.

Lesson 1 of the Monte Carlo family. Next: importance sampling, MCMC, Hamiltonian Monte Carlo, sequential Monte Carlo, quasi-Monte Carlo and Monte Carlo tree search.

Run the dartboard 20 times

Every run is real: N uniform darts in the unit square, estimate = 4 × hits / N. The purple band is one standard error, 1.64 / √N (Chapter 3). The square shows at most 1,500 darts of the current run.

Chapter 0

Throw Darts to Find π

Turn a number you cannot compute into a count of random hits

You need the number π. You have no formula and no calculator. You have a square board, one unit on each side, with a quarter circle of radius 1 drawn from one corner.

Throw darts so that every spot on the square is equally likely. The square has area 1. The quarter circle has area π/4. So a dart lands inside with probability π/4, and four times the fraction inside estimates π.

That is Monte Carlo: replace a quantity you cannot compute with the average result of random trials. Each random trial is a sample. The number the method reports is the estimate.

Throw darts and watch π appear

Teal darts land inside the quarter circle; grey darts miss. The warm line is the running estimate. Throw more and watch it settle inside the purple funnel.

Real uniform darts from a seeded generator. The funnel is π ± one standard error, 1.64 / √N. The board stops at 10,000 darts.

Write the method down. Call the number of darts N. Call the darts that land inside the hits, and their count H.

Say it aloud

Pi-hat equals four times H over N.

π̂
pi-hat the estimate of π. The hat means "estimated from samples".
4
four undoes the quarter: the quarter circle covers π/4 of the square.
H
H the hits: darts with x² + y² ≤ 1.
N
N the number of darts thrown.
In plain words

Throw N darts. Count the hits H, the darts whose x squared plus y squared is at most 1. Divide H by N and multiply by 4.

With numbers

The eight fixed darts below give H = 6 and N = 8. So pi-hat = 4 × 6 / 8 = 3.0. The true value is 3.14159.

Dart(x, y)x² + y²Inside?
1(0.1, 0.2)0.05yes
2(0.4, 0.5)0.41yes
3(0.3, 0.6)0.45yes
4(0.5, 0.5)0.50yes
5(0.9, 0.5)1.06no
6(0.7, 0.6)0.85yes
7(0.2, 0.4)0.20yes
8(0.95, 0.6)1.2625no

3.0 is not a mistake. It is one noisy draw from a method that is right on average. With 8 darts, a typical estimate lands about 0.58 from π. Chapter 3 shows where that number comes from.

The failure, as symptom, measurement and fix

The symptom: two runs disagree, say 3.0 and 3.5, and you suspect a bug. To measure, rerun the same code 20 times and look at the spread, as the hero does. The fix is more darts. But the spread shrinks slowly: 100 times the darts makes it 10 times smaller. That law is the spine of this lesson.

The road

  1. An average is an integral: average random heights to get an area.
  2. Why the average settles: the law of large numbers.
  3. Measure your own error: the standard error, σ / √N, the purple band in the hero.
  4. The iron law: the cost of each extra digit.
  5. Error bars you can trust: confidence intervals and what 95% means.
  6. High dimensions: where grids collapse and Monte Carlo does not.
  7. Price an option: the showcase, a fan of simulated futures.
  8. Neutrons and grainy pixels: where the name came from, and why renders are noisy.
  9. Same answer, fewer samples: shrink σ instead of growing N.
  10. Field guide: terms, numbers, code and the family.
Eight darts give an estimate of 3.0. A friend throws eight more and gets 3.5. What is the honest conclusion?

Chapter 1

An Average Is an Integral

Average the heights at random points to get the area under a curve

You want the area under f(x) = x² between 0 and 1. Pretend you forgot calculus. (The answer is 1/3.)

An area is its average height times its width. Here the width is 1. So pick x at random between 0 and 1, read the height f(x), and repeat. The average of the heights is the area. The dartboard did the same thing: its "height" was 1 inside the circle and 0 outside.

Average random heights

Each teal stick is one sample of the height. The warm bar is their average. Press Resample a few times, then Repeat 50 times and watch where the repeats centre.

5

Real uniform samples of f(x) = x² on [0, 1]. The yellow line is the exact area, 1/3.

Now the general rule. Call the interval from a to b. Draw N points, each equally likely anywhere in it, and call point number i xi. Call the area I.

Say it aloud

I is about b minus a, times one over N, times the sum over i of f of x-i.

I
I the integral: the area under f between a and b.
≈
is about the right side is an estimate, not the exact value.
(b − a)
b minus a the width of the interval.
(1/N)
one over N divide by the number of samples, to make an average.
Σi
the sum over i add one term for each sample, i = 1 to N.
f(xi)
f of x-i the height of the curve at random point i.
In plain words

Draw N random points x-i between a and b. Average their heights f of x-i. Multiply the average by the width b minus a.

With numbers

On [0, 1] with points 0.1, 0.5 and 0.9: the heights are 0.01, 0.25 and 0.81. Their average is 1.07 / 3 = 0.357, and the width is 1, so I ≈ 0.357. The true area is 0.333.

0.357 is a little high. That is fine. The estimator has no bias; we call it unbiased. If you repeat the whole experiment many times, the average of the estimates equals the true area exactly, for any N. We checked with 200,000 repeats of three points: the mean estimate was 0.3334.

The failure, as symptom, measurement and fix

The classic bug is a missing width. Estimate the area under f(x) = x on [1, 3], true value 4.5, with points 1.5, 2.0 and 2.5. The average height is 2.0, and without the width you report 2.0.

The symptom is an answer off by the same factor on every run. To measure, test the code on f(x) = 1, whose integral is the width b − a. The fix: multiply by b − a, and 2.0 × 2 = 4.0.

Uniform points are one choice. Draw points from a smarter distribution and reweight them, and you get importance sampling, the next lesson in the family.

A Monte Carlo estimator of an integral is unbiased. What does that guarantee?

Chapter 2

Why the Average Settles

See the running mean funnel onto the truth, and why the count does not

Roll a fair die and keep a running average. The true mean of a die is 3.5. Here are six fixed rolls.

RollValueRunning sumRunning mean
1222.000
2573.500
3182.667
46143.500
53173.400
64213.500

Early on the mean lurches. With more rolls it stays near 3.5. The law of large numbers says this always happens: the running mean of independent samples converges to the true mean as N grows. It is the theorem that makes Monte Carlo legal.

Add running means

Each warm trace is the running mean of its own stream of rolls, on a log scale of N. Add traces. They start in different places and all enter the purple funnel.

Real seeded rolls, 2,000 per trace. The funnel is the true mean ± one standard deviation of the running mean, σ / √n.

Why does it settle? Roll number n counts for only 1/n of the average. Later rolls dilute an early streak of low rolls; they do not correct it. The die is never "due" for a 6.

So the raw count can drift while the fraction settles. Flip a fair coin. Call heads minus half the flips the imbalance. Its typical size (one standard deviation) grows like 0.5 √N. The fraction's error is that imbalance divided by N, so it shrinks like 0.5 / √N.

Flips NTypical imbalance, 0.5 √NTypical fraction error, 0.5 / √N
10050.05
10,000500.005
1,000,0005000.0005

The failure, as symptom, measurement and fix

The law needs independent samples. The symptom of broken independence: each worker's running mean settles, but on a different value. To measure, plot several traces with different seeds: they must funnel to one value. A common cause is every worker starting from the same seed. The fix: give each worker its own random stream.

After 1,000 fair coin flips you have 470 heads, 30 short of 500. What does the law of large numbers say about the next flips?

Chapter 3

Measure Your Own Error

Compute how far your average can be from the truth, from the samples alone

You flip a coin 100 times and report a heads rate of 0.50. Could the truth be 0.43? You never get infinite samples, so you need the size of your error. Monte Carlo can measure it from the same samples.

Two spreads matter. The standard deviation, σ (sigma), is the spread of single samples. A coin flip is 0 or 1, never 0.5, and that spread stays the same no matter how long you flip. The standard error is the spread of the average. It shrinks as N grows.

Compare the two spreads

Left: 2,000 single samples of x², a lopsided shape. Right: 400 averages, each of N samples. Slide N and watch only the right shape narrow.

10

Real samples of f(U) = U² with U uniform on [0, 1]. Its exact σ is 0.298. The purple bracket marks ± σ / √N around the true mean 1/3.

Where does the square root come from? Variance is the square of the spread, σ². Variances of independent samples add, so a sum of N samples has variance Nσ². The average divides the sum by N, and a constant comes out of a variance squared:

variance of the average = (1/N)² · Nσ² = σ² / N

Take the square root to get back to a spread. That is the standard error, SE.

Say it aloud

S-E equals sigma over the square root of N.

SE
S-E the standard error: how far the average typically lands from the truth.
σ
sigma the spread of one sample. A fair coin has σ = 0.5.
√N
root N the square root of the number of samples.
In plain words

Measure the spread sigma of single samples. Divide it by the square root of N. The result is how far your average typically sits from the truth.

With numbers

A fair coin has sigma = 0.5. At N = 100, SE = 0.5 / 10 = 0.05. At N = 10,000, SE = 0.5 / 100 = 0.005: 100 times the flips for 10 times the precision.

Usually you do not know σ. Estimate it from the samples. Take five heights: 0.2, 0.9, 0.4, 0.7, 0.3.

  1. The mean is 2.5 / 5 = 0.50.
  2. The squared distances from the mean are 0.09, 0.16, 0.01, 0.04, 0.04. They sum to 0.34.
  3. Divide by N − 1 = 4 (this small correction keeps the estimate fair on tiny samples): 0.085. The square root is s = 0.29.
  4. SE = 0.29 / √5 = 0.13. Report 0.50 ± 0.13.

The dartboard from Chapter 0 fits too. One dart's hit has σ = √(0.785 × 0.215) = 0.41, and the estimate multiplies by 4, so its spread is 1.64. At N = 8, SE = 1.64 / √8 = 0.58.

The failure, as symptom, measurement and fix

The symptom: error bars that stay the same width when you run 10 times longer. The code reports σ, the sample spread, as the error. To measure, double N: a true standard error shrinks by 1.41. The fix is to divide by √N.

Your estimate has a standard error of 0.04 at N = 2,500. What is the standard error at N = 10,000?

Chapter 4

The Iron Law: Half the Error, Four Times the Work

Turn the standard error around to price each extra digit in samples

Your estimate of π is good to one decimal. Your manager wants two. How many more samples? Read SE = σ / √N backwards. Call the error you want ε (epsilon), and solve for N.

Say it aloud

N equals sigma over epsilon, squared.

N
N the number of samples you need.
σ
sigma the spread of one sample, from a short pilot run.
ε
epsilon the standard error you want to reach.
2
squared multiply the ratio by itself. This square is the whole cost.
In plain words

Divide the sample spread sigma by the error epsilon you want. Square the result. That is how many samples N you need.

With numbers

A coin has sigma = 0.5. For epsilon = 0.01: N = (0.5 / 0.01)² = 50² = 2,500 flips. For epsilon = 0.005: N = 100² = 10,000. Half the error costs 4 times the flips.

This is the iron law of Monte Carlo. Halving the error needs 4 times the samples. One more decimal digit, 10 times smaller, needs 100 times the samples. Doubling N improves the error by only √2 = 1.41.

Target error εSamples N = (0.5 / ε)²Against the row above
0.05100start
0.025400error × 1/2, N × 4
0.01251,600error × 1/2, N × 4
0.006256,400error × 1/2, N × 4

Price a target error in samples

The purple line is σ / √N for a coin; the dots are errors we measured. Slide the target and read the blue cost on the N axis.

0.01

Dots: the root mean square error of a fair-coin estimate over 30 seeded repeats at each N. The line has slope −1/2 on log axes: that slope is the law.

No sampler beats the √N in the formula; it comes from the variance of an average. The one other lever is σ. Shrinking σ is Chapter 9.

The failure, as symptom, measurement and fix

The symptom: a job planned as "twice as long for twice the accuracy" runs four times longer and still misses. To measure, do a pilot run of 1,000 samples and estimate σ. Then the fix: plan with N = (σ / ε)², or reduce σ.

A render is too grainy and you want half the noise. By what factor must the number of ray samples grow?

Chapter 5

Error Bars You Can Trust

Wrap the estimate in an interval that catches the truth 95 times in 100

A trader asks: "Your price is 10.45. How sure are you?" A standard error is a size, not a promise. To promise something, you need the shape of the error.

The central limit theorem gives that shape. The average of many independent samples has a bell-shaped (normal) spread around the truth, with width SE. This holds even when single samples look nothing like a bell: coin flips, lopsided payoffs, anything with a finite spread.

So build an interval. Call the estimate μ̂ (mu-hat). Call the number of standard errors you step out z.

Say it aloud

Mu-hat plus or minus z times S-E.

μ̂
mu-hat the estimate: the average of the samples.
±
plus or minus go the same distance down and up.
z
z how many standard errors: 1.645 for 90%, 1.96 for 95%, 2.576 for 99%.
SE
S-E the standard error, s / √N.
In plain words

Compute the average mu-hat and its standard error SE. Multiply SE by z. Step that far below and above mu-hat. The two ends are the interval.

With numbers

With made-up numbers: mu-hat = 0.30, s = 0.46, N = 400. SE = 0.46 / 20 = 0.023. For 95%, z · SE = 1.96 × 0.023 = 0.045. The interval is 0.255 to 0.345.

ConfidencezHalf-width at SE = 0.023
90%1.6450.038
95%1.9600.045
99%2.5760.059

What does 95% mean? The truth is fixed. The interval moves each time you rerun. Run the whole experiment many times, and about 95% of the intervals catch the truth. We checked: 10,000 runs of the example above caught it 95.1% of the time.

Run 20 experiments

Each row is one experiment: a warm estimate and its interval. Green intervals catch the yellow truth; red ones miss. Run a few batches and watch the total.

400

Each experiment flips N coins with a true heads rate of 0.30 and builds μ̂ ± z · s / √N. Seeded, real draws.

The failure, as symptom, measurement and fix

The bell is an approximation. With small N or strongly lopsided samples, a "95%" interval can catch the truth only 90% of the time. To measure, run the coverage test on a problem with a known answer, as the device does. The fix is more samples, or a method that does not assume a bell, such as the bootstrap.

You build a 95% interval, 0.255 to 0.345. Which statement is correct?

Chapter 6

Why Monte Carlo Wins in High Dimensions

Count the points a grid needs, and see why random points do not care about dimension

1 / √N is slow. Why not use a regular grid of points? In one dimension a grid wins easily. The trouble starts when the integral has many inputs.

Put m points along each axis. In d dimensions that is md points. Ten points per axis in 10 dimensions is 1010, ten billion. Turn it around: a fixed budget of N points gives the grid only N1/d points per axis, so the spacing between grid points is

h = N−1/d   (the spacing, for N points in d dimensions)

Raise the dimension

Blue bars are point counts on a log scale. Slide d and watch the grid bar run off the chart while the Monte Carlo bar stays put. The ticks show how coarse a 1,000,000-point grid gets.

3

Counts are exact arithmetic. "Monte Carlo error σ / 1,000" assumes 1,000,000 samples; σ depends on the function and can grow with d.

A grid rule's error shrinks like a power of its spacing, hk. The midpoint rule has k = 2 for smooth functions, so its error shrinks like N−2/d. Monte Carlo's error shrinks like N−1/2 in every dimension. Monte Carlo has the better rate once 1/2 > k/d, that is, for d > 2k: above 4 dimensions for the midpoint rule.

Dimension dGrid points at 10 per axisPoints per axis from 1,000,000
21001,000
61,000,00010
1010,000,000,0004
2010202

A test in 5 dimensions, with 16,807 points each (7 per axis for the grid). For the smooth sum of squares, true value 5/3, the midpoint grid misses by 0.0085 and Monte Carlo by 0.0041. For a step function that is 1 when the coordinates sum past 2.5, the grid misses by 0.032 and Monte Carlo by 0.003. Grids suffer most on rough functions.

The failure, as symptom, measurement and fix

The symptom: nested loops over every parameter, and each new parameter makes the run 10 times slower. To measure, count the evaluations, md. The fix is random points, or the structured points of quasi-Monte Carlo, which fill space more evenly than random ones.

Why does Monte Carlo beat a midpoint grid for a smooth function of 12 variables?

Chapter 7

Price an Option by Averaging Futures

Simulate thousands of possible stock prices, pay each one out, and average

You sold a European call option: the buyer may buy a share at a fixed strike price K = 100 in one year. If the share then trades at ST, the option pays max(ST − K, 0). Its value today is an average over possible futures.

One rule decides the answer: simulate the stock growing at the risk-free rate r, not at the return you forecast. Only this gives a price with no risk-free profit. The volatility, the stock's yearly random swing, is σ in finance books. We call it v, because σ already means a sample's spread.

Call today's price S0, the years to expiry T, and a standard bell-curve draw Z. One simulated price is:

Say it aloud

S-T equals S-zero times e to the power of: r minus v squared over 2, times T, plus v times root T times Z.

ST
S-T one simulated share price at expiry.
S0
S-zero today's price, 100.
exp
e to the power of turns growth into a multiplier, so the price stays above 0.
r
r the risk-free rate, 0.05 a year.
v
v the volatility, 0.20 a year. The minus v squared over 2 keeps the average growth at exactly r.
T
T the time to expiry, 1 year.
Z
Z a standard bell-curve draw: the luck of this future.
In plain words

Draw Z. Add the steady growth, r minus half v squared, times T, to the random shock, v times root T times Z. Raise e to that sum and multiply by S-zero.

With numbers

With Z = 0.5: growth (0.05 − 0.02) × 1 = 0.03, shock 0.20 × 1 × 0.5 = 0.10. S-T = 100 × e0.13 = 113.88.

Now pay out and average. Call future number i's price ST,i. Money in a year is worth less today, by the factor e−rT. Call today's price C.

Say it aloud

C is about e to the minus r T, times one over N, times the sum over i of: the max of S-T-i minus K, and zero.

C
C the call's fair price today.
e−rT
e to the minus r T the discount: 0.951 for one year at 5%.
(1/N) Σi
one over N, the sum over i the average over N futures.
max(ST,i − K, 0)
the max of S-T-i minus K, and zero future i's payoff: its gain over K, or 0.
In plain words

Pay each future i the amount S-T-i minus K, or zero if that is negative. Average the payoffs. Multiply by e to the minus r T.

With numbers

Future 1 (Z = 0.5) pays 13.88, worth 0.951 × 13.88 = 13.21 today. Future 2 (Z = −1.0) ends at 84.37 and pays 0. With N = 2, C ≈ 13.21 / 2 = 6.60.

This simple call has a closed form, the Black–Scholes formula of 1973: 10.4506. 200,000 futures (seed 0) give 10.464 with SE = 14.73 / √200,000 = 0.033, and the 95% interval 10.464 ± 0.065 holds 10.4506. Payoffs that depend on the whole path have no formula; the recipe stays the same.

Price the call

Teal futures finish above the strike and pay; grey ones pay nothing. Stream paths, then move the strike far out and watch the purple band widen.

0.20
100

S0 = 100, r = 0.05, T = 1. Exact risk-neutral paths on 20 steps; the yellow line is the Black–Scholes closed form.

At K = 140 only 6% of futures pay. At 10,000 futures the relative error is 5%, against 1.4% at K = 100. Importance sampling steers samples toward the paying region.

The failure, as symptom, measurement and fix

The symptom: a price of 13.97 instead of 10.45. The code grew the stock at a forecast 10% instead of r = 5%. To measure, check a plain call against Black–Scholes first. The fix: grow at r.

200,000 simulated futures give a price with SE = 0.033. How many futures give SE = 0.0165?

Chapter 8

Neutrons and Grainy Pixels

Follow cheap random histories to a probability, and see render noise as a standard error

In 1946 at Los Alamos, Stanislaw Ulam was recovering from an illness and playing solitaire. He wondered what fraction of games could be won. Instead of the combinatorics, he thought: deal many games and count. With John von Neumann he applied the idea to neutrons in shielding. Nicholas Metropolis suggested the name Monte Carlo, after the casino where Ulam's uncle liked to gamble.

A neutron in a slab hits a nucleus. The nucleus absorbs it (probability 0.3), or it leaks out (0.2), or it scatters and flies on (0.5). One history, the life of one neutron, ends in one verdict: leaked or not. The leak probability is the fraction of leaks over many histories.

Release neutrons

Teal tracks are recent histories: grey dots are absorptions, arrows are leaks. Release a batch, then change the odds and release again.

0.30
0.20

The fate at each collision is a real random draw with the chosen odds. The track geometry is illustrative; it does not change the verdict.

The exact answer: a scatter only delays the verdict. So the outcome is a race between leak and absorb.

P(leak) = 0.2 / (0.2 + 0.3) = 0.4

A collision ends the history with probability 0.5, so a history lasts 1 / 0.5 = 2 collisions on average. Histories are cheap. 200,000 of them gave 0.4012 ± 0.0011, which is SE = √(0.4 × 0.6 / 200,000) from Chapter 3.

Pixels: the same estimator

A path tracer, the kind of renderer used for film, sets each pixel to the average light carried by random rays. Too few rays and the image is grainy. That grain is the standard error, made visible.

Four rays return 0.2, 0.8, 0.5 and 0.1. The pixel is 0.40, s = 0.316, SE = 0.316 / 2 = 0.158. Pixels differ in σ. At 64 rays, a matte wall with σ = 0.05 has SE = 0.006. A glint with σ = 0.6 has SE = 0.075: 12 times noisier, so it needs 12² = 144 times the rays to match.

Add rays per pixel

Each square is one pixel, the average of its rays. Both halves have the same true brightness, 0.4. Step up the rays and see which half cleans up first.

Toy rays, not a renderer: a matte ray returns 0.4 ± 0.05 (bell-shaped); a glint ray returns 1.3 with probability 4/13, else 0 (mean 0.4, σ = 0.6).

The failure, as symptom, measurement and fix

The symptom: highlights stay speckled long after walls are clean. To measure, estimate each pixel's σ from a first batch of rays. The fix: send more rays where σ is high. A denoiser can also smooth the grain, but it trades noise for bias: compare it against a high-ray reference.

A frame is grainy at 64 rays per pixel. To halve the visible noise, render at about:

Chapter 9

Same Answer, Fewer Samples

Shrink sigma instead of growing N, and keep the estimate unbiased

SE = σ / √N has two parts. You cannot change the √N. You can shrink σ, and cutting the variance 30 times is worth 30 times the samples. This is variance reduction. The test problem: the integral of ex on [0, 1], true value e − 1 = 1.7183. One plain sample has variance 0.2420.

TechniqueWhat it doesWhen it helps
Antithetic variatesPair each draw u with its mirror 1 − u.f rises or falls steadily.
Control variatesSubtract a related quantity with a known mean, then add the mean back.A cheap helper tracks f closely.
Stratified samplingCut the range into equal bins and put one sample in each.Almost always; it never hurts on equal bins.
Common random numbersReuse the same random draws for two systems you compare.You need a difference, not two levels.

Take antithetic variates. Since ex rises, a high f(u) comes with a low f(1 − u). Two quantities that move in opposite directions have a negative covariance, a measure of how they move together. Call the variance of one sample σ² and the covariance of f(u) with f(1 − u) c. The average of one mirror pair, θ̂ (theta-hat), has this variance:

Say it aloud

The variance of theta-hat equals sigma squared plus c, over 2.

Var(θ̂)
the variance of theta-hat the spread, squared, of the pair average (f(u) + f(1 − u)) / 2.
σ2
sigma squared the variance of one plain sample, 0.2420 here.
c
c the covariance of f(u) and f(1 − u): negative when they move in opposite directions.
/ 2
over 2 the pair holds two samples.
In plain words

Add the covariance c to the single-sample variance sigma squared, then halve. If c is close to minus sigma squared, almost nothing is left.

With numbers

sigma squared = 0.2420 and c = −0.2342. Var(theta-hat) = (0.2420 − 0.2342) / 2 = 0.0039. Two plain samples give 0.2420 / 2 = 0.1210. Same two evaluations, 31 times less variance.

The control variate uses the helper g(u) = u, whose mean, 1/2, we know. The estimator is f(u) − b(u − 1/2). The best weight b is the covariance of f and g divided by the variance of g:

b = 0.1409 / 0.0833 = 1.69  →  variance 0.2420 − 0.1409² / 0.0833 = 0.0039

That is 61 times less than plain, because u and eu are 99% correlated. Stratifying [0, 1] into two halves gives 0.0325 against 0.1210, 3.7 times less. With one sample in each of 64 bins it is about 3,700 times less, since ex is nearly flat inside a tiny bin.

Race four estimators

Each bar is the measured variance of one estimator over 200 repeats, on a log scale. Warm is plain Monte Carlo; pink bars are the improved estimators. Change N and measure again.

64

All four estimate the integral of ex on [0, 1] with the same N evaluations; the control variate uses the exact b = 1.69. Real seeded draws.

The failure, as symptom, measurement and fix

Antithetic pairs can hurt. For f(u) = (u − 1/2)², f(u) equals f(1 − u), so each pair holds one sample twice. We measured twice the plain variance at equal cost. The symptom is no gain, or a loss. To measure, compare variances over repeats at equal evaluations. The fix: use mirrors only when f rises or falls steadily.

One more trick reshapes the sampling itself: draw from a smarter distribution and reweight. That is importance sampling. In reinforcement learning, the baseline in policy gradients is a control variate.

At N = 10,000 a control variate cuts the variance 16 times. How many plain samples give the same standard error?

Chapter 10

Field Guide

Keep the terms, the numbers, the code and the family in one place

Monte Carlo writes a quantity as an average, draws random samples, and averages them. The law of large numbers makes it converge. The standard error, σ / √N, says how far off it is. The iron law prices accuracy: 100 times the samples for one more digit. The rate ignores dimension, so it rules high-dimensional problems. Variance reduction attacks σ, the only other lever.

Terms and numbers

TermMeaningNumber from this lesson
EstimateThe average of the samples.8 darts: π̂ = 3.0
UnbiasedThe estimates centre on the truth.Mean of 200,000 three-point estimates: 0.3334 (truth 1/3)
Standard deviation σSpread of one sample.Coin: 0.5. One dart, times 4: 1.64
Standard errorSpread of the average, σ / √N.Coin at N = 100: 0.05
Iron lawN = (σ / ε)².ε = 0.01 for a coin: 2,500 flips
95% intervalμ̂ ± 1.96 SE.0.30 ± 0.045; coverage 95.1%
Grid costmd points; Monte Carlo wins on rate above d = 2k.10 per axis, d = 10: 1010
Call priceDiscounted average payoff.10.464 ± 0.065 vs 10.4506
Variance reductionSame centre, smaller σ.Antithetic 31×, control 61×

Checklist before you trust a Monte Carlo number

The core in code

pythonimport numpy as np

def monte_carlo(sample, N, rng, z=1.96):
    x = sample(rng, N)                      # N samples, shape (N,)
    est = x.mean()                          # the estimate
    se  = x.std(ddof=1) / np.sqrt(N)          # its standard error, from the same data
    return est, (est - z*se, est + z*se)       # and its 95% interval

rng = np.random.default_rng(0)
darts = lambda r, n: 4.0 * ((r.random((n, 2))**2).sum(1) <= 1)   # 4 x (hit or miss)
print(monte_carlo(darts, 100_000, rng))      # about 3.14, SE about 0.005

N_needed = int(np.ceil((0.5 / 0.01)**2))      # iron law: 2500 flips for SE 0.01

Where you meet it

PlaceWhat gets averagedLesson
Reinforcement learningReturns of sampled episodes, to estimate a value or a gradient.Policy gradients
Bayesian inferenceA function over samples of the parameters.MCMC, HMC
TrackingWeighted particles that follow a moving state.Sequential Monte Carlo, particle filter
Game play and planningOutcomes of random play-outs from each move.MCTS
Diffusion modelsThe training loss, over random noise levels and noise draws.Diffusion

The family

LessonWhat it adds to plain Monte Carlo
Importance samplingDraw from a smarter distribution and reweight; rescues rare events.
MCMCSamples from a distribution you can evaluate but not draw from.
Hamiltonian Monte CarloUses gradients to make long, accepted MCMC moves.
Sequential Monte CarloUpdates a cloud of weighted samples as data arrives.
Quasi-Monte CarloEvenly spread points that beat 1 / √N on smooth integrands.
Monte Carlo tree searchTurns random play-outs into a search over decisions.
The takeaway. Any quantity you can write as an average, you can estimate by sampling, and the samples tell you their own error. The price is fixed: the error falls like 1 / √N. So shrink σ first, then buy N.

Sources

N. Metropolis and S. Ulam, "The Monte Carlo Method", Journal of the American Statistical Association 44 (1949). N. Metropolis, "The Beginning of the Monte Carlo Method", Los Alamos Science, Special Issue (1987), for the history in Chapter 8. F. Black and M. Scholes, "The Pricing of Options and Corporate Liabilities", Journal of Political Economy 81 (1973), for the reference price. Every other number on this page comes from our own seeded runs.

Now press Present or Teach. Explain from memory why 4 × hits / N estimates π, why the error is σ / √N, and what one more digit costs. Then go back to the dartboard and predict how tight the 20 dots get at 10,000 darts before you press it.

Monte Carlo Simulation · Lesson 1 of the Monte Carlo family
Next: Importance sampling · Back to Gleams