Plain sampling needs about 316,000 draws just to see ten days past 4 standard deviations. Draw from a shifted distribution, weight each draw by p/q, and 1,000 draws land within about 7% of the truth.
Pick a sampler, set the threshold, then press Draw 1,000. Watch where the draws land and what each sampler reports. Then we build, piece by piece, the weight, its variance, the best proposal, the health check and five places the idea runs today.
You need Monte Carlo (an average of random draws estimates an expectation; see the Monte Carlo lesson) and a little Python. We build the rest from zero.
The target is the standard bell curve N(0,1) and the event is X > t. Importance sampling draws from q = N(t, 1). The truth is the exact normal tail. The draws are random, so each press gives a new run.
Chapter 0
Count how few plain draws land in a rare region, and measure how bad the estimate gets
An insurer asks: what is the chance that tomorrow's loss passes 4 standard deviations? You have a model of one day's loss, so you simulate a thousand days and count. The counter most likely stays at zero.
Call a day's standardized loss X, drawn from the standard bell curve N(0,1). The rare event is X > t for a threshold t. Crude Monte Carlo (plain sampling) estimates the event's probability as the share of draws that pass t. Most draws land in the bulk and tell you nothing.
Teal is the bell curve p. Each dot is one draw. Blue marks the threshold. Press Run, then push t to the right and watch the hit counter stall.
Draws come from N(0,1) through a seeded random generator. The truth is the exact normal tail.
How noisy is the share? Call the true probability p and the number of draws N. Each draw is a coin that lands 1 with chance p. The typical error of the share, divided by p itself, is the relative error.
Rel equals the square root of one minus p, over p times N.
Divide one minus p by p times N. Take the square root. A small p makes the bottom small, so rel grows.
At t = 4, p = 0.0000317. With N = 1,000,000: rel = √(0.99997 / 31.7) = 0.18, an 18% error. With N = 1,000, rel = 5.6, and 97% of runs see no hit at all.
The failure. Symptom: the estimate is 0, or it jumps between 0 and a large value from run to run. Measure: count the hits. Fewer than 100 hits means more than 10% error. Fix: sample somewhere else. A one-in-a-million event needs about 100 million plain draws for 10% error.
So keep the same truth but change where you look. Draw from a distribution that visits the rare region often. Then multiply each draw by an honest correction, so the answer stays exact.
Chapter 1
Draw from a proposal you choose and correct each draw with the weight p/q
Call the distribution you care about the target p. Call the distribution you draw from the proposal q. You choose q, so you can make it visit the places that matter.
The draws now over-represent some places and under-represent others. Each draw x gets a correction, the importance weight: the target density at x divided by the proposal density at x. Where q over-produces, the weight is below 1. Where q under-produces, it is above 1.
The correction is exact. Multiply and divide by q inside the average:
The only condition: q must be above zero wherever p times f is not zero. You cannot reweight a place you never sample.
Now the estimator. Call the function you average f. Draw N values x1 to xN from q. Call the estimate μ̂ (mu-hat).
Mu-hat equals one over N times the sum over i of w of x-i times f of x-i, where w of x is p of x over q of x.
Draw each x-i from q. Multiply f of x-i by its weight w of x-i. Average the products. That is mu-hat.
Target p = N(0,1), proposal q = N(0, 1.5), f(x) = x², truth 1. Three draws: 0.5, −2.0, 1.0. Weights 1.40, 0.49, 1.14. Products 0.35, 1.98, 1.14, total 3.46, so μ̂ = 1.15. The plain average of x² over the same draws is 1.75.
Teal is p, pink is q. Dots are draws from q, sized by their weight. Drag q's centre and width. The orange running estimate of Ep[x²] heads for the yellow truth unless q is a poor match.
Each setting draws 3,000 values from q with a fixed seed. The truth Ep[x²] = 1 is exact.
You can write the weights by hand when both densities are bell curves. With p = N(0,1) and q = N(3,1), the √(2π) factors cancel:
The failure. Symptom: the estimate settles, but on the wrong value. Take q uniform on [−2, 2]: it never draws the tails, so μ̂ converges to 0.74, not 1. Measure: check that q covers every place where p times f is large. Fix: widen q or give it heavier tails.
Chapter 2
Find where the variance comes from, and see a narrow proposal make it infinite
Run the same estimator twice, same target, same N, two proposals. One settles in a few hundred draws. The other sits still for thousands of draws, then jumps. Both are unbiased. The difference is the variance: how far one estimate tends to land from the truth.
The variance of μ̂ is the variance of one product w·f under q, divided by N. Call the per-draw variance σ²IS and the true answer μ.
Sigma squared I-S equals the integral over x of p of x squared, times f of x squared, over q of x, minus mu squared.
At every x, square p times f and divide by q. Add it all up. Subtract the true answer squared. Where q is tiny but p times f is not, the division blows up.
p = N(0,1), f = x², μ = 1. With q = p the integral is 3, so σ²IS = 2. With q = N(0, 1.5) it is 1.49, so σ²IS = 0.49, four times better. With q = N(0, 0.8) it is 18.
For a bell-curve q of width σq, the ratio p²/q shrinks in the tails only while σq is above 1/√2 = 0.707. Below that it grows without end, so the integral is infinite. The estimate stays unbiased. Its variance is infinite.
Top: the variance per draw against q's width, with the red wall at 0.707. Bottom: one run of 4,000 draws. Slide the width below 0.7 and watch the run lurch.
Target N(0,1), f = x², q = N(0, width). The curve is exact: σ² = 3s / (4√2 · a2.5) − 1 with a = 1 − 1/(2s²). The run is a seeded simulation.
The failure. Symptom: a running mean that sits flat, then leaps when one draw arrives. Measure: the largest weight over the sum of weights. In one run of 200,000 draws with width 0.5, one weight reached 726 and the sample variance was 209. Fix: give q heavier tails than p times |f|. Here the best bell width is √3 = 1.73, with σ²IS = 0.45.
Chapter 3
Shape q like p times |f| and every weighted draw returns the same number
If q sets the variance, which q is best? Put draws where p times |f| is large and none where it is zero. Push that idea to its limit.
Call the area under p times |f| Z. Dividing by Z makes the shape a proper distribution, one that adds up to 1. Call that distribution q* (q-star).
Q-star of x equals the absolute value of f of x, times p of x, over Z.
Multiply |f| by p at every x. Scale the curve by Z so its area is 1. Draw from that shape. When f is never negative, every product w times f then equals Z.
p = N(0,1) and f = x², so Z = 1 and q* = x² p(x). At x = 2: w = p/q* = 1/4, and w·f = 1/4 × 4 = 1. At x = 0.5: w = 4, and w·f = 4 × 0.25 = 1. Every draw returns 1, the exact answer, so the variance is 0.
Top: p (teal), q* (blue) and your blend q (pink). Bottom: w·f at ten fixed points. Slide the blend toward q* and watch the bars level at the yellow line, Z = 1.
q = (1 − blend) · p + blend · q*. The variance is a numerical integral on a fine grid: 2 at blend 0, 0.31 at 0.5, 0.028 at 0.9, 0 at 1.
Now the catch. Z is the average of |f| under p. For f that is never negative, Z is the answer you want. If you could write q*, you would not need to sample. So q* is a direction, not a recipe: shape q like |f| times p, and keep its tails heavy (Chapter 2).
The failure. Symptom: a q shaped like |f|·p still leaves variance when f changes sign. For f = x, q* = |x| p / Z gives w·f = +Z or −Z, a variance of Z² = 0.64. Measure: look at the sign of the w·f values. Fix: split f into its positive and negative parts, and give each part its own proposal.
Chapter 4
Turn a list of weights into a count of plain draws
You drew 1,000 weighted draws. One weight is 100 and the rest are 1. The weighted average mostly repeats that one draw. How many plain draws is the set worth?
Call the weights w1 to wN. The effective sample size (ESS) is the number of equal-weight draws that would carry the same information. This form is Kish's, from survey sampling.
E-S-S equals the sum over i of w-i, squared, divided by the sum over i of w-i squared.
Add the weights and square the total. Square each weight and add those. Divide the first by the second. Equal weights give N. One dominant weight gives about 1.
Weights 1, 1, 1, 1, 100. The sum is 104, squared 10,816. The squares add to 10,004. ESS = 10,816 / 10,004 = 1.08. Five draws are worth about one. Weights 0.1, 0.2, 0.05, 4.0, 0.3 give 21.62 / 16.14 = 1.34.
Twelve purple bars show the normalized weights. Drag the skew to pile weight onto fewer draws and watch ESS fall from 12 toward 1.
Illustrative weights: wi = ri for i = 0 to 11, with r = eskew · 1.2.
The failure. Symptom: ESS/N far below 1. Measure: compute ESS every run. As a rule of thumb, ESS/N under 0.1 is a stop sign. Fix: re-centre or widen q, or add rungs between q and p (Chapter 9).
ESS has a blind spot. It judges the weights of the draws you have, never the places you did not draw. The uniform proposal on [−2, 2] from Chapter 1 scores a healthy ESS/N of 0.81 and still converges to 0.74 instead of 1.
Chapter 5
Divide by the sum of the weights so an unknown scale cancels, and pay a small bias
In Bayesian inference the posterior is the likelihood times the prior, divided by the evidence. The evidence is an integral you usually cannot compute. So you know the target's shape, p̃ (p-tilde), but not its scale: p̃(x) = c · p(x) for an unknown constant c.
Plain importance sampling with p̃ in the weight returns c times the answer. The fix is to divide by the sum of the weights. The constant c sits in the top and the bottom, so it cancels. This is self-normalized importance sampling (SNIS).
Mu-hat S-N equals the sum over i of w-tilde-i times f of x-i, divided by the sum over i of w-tilde-i, where w-tilde-i is p-tilde of x-i over q of x-i.
Weight each draw by p-tilde over q. Take the weighted total of f. Divide by the total weight. As a bonus, the average w-tilde estimates the hidden scale c.
Target N(1,1), known only as p̃(x) = exp(x − x²/2), and proposal q = N(0,1). Drop the constants: w̃ = ex. Draws −1, 0, 1, 2 give w̃ = 0.37, 1, 2.72, 7.39, total 11.48. The weighted total of x is 17.13. So μ̂SN = 17.13 / 11.48 = 1.49. The truth is 1.
The target is known only up to c. Drag c: the pink plain estimate moves with it, the purple self-normalized one stays put. Pick N to see the small-N bias.
Each histogram is 600 repeated runs with a fixed seed. Target N(1,1), proposal N(0,1), f = x.
The failure. Symptom: small runs sit off the truth on average. SNIS divides one random sum by another, and that ratio is biased. In this example the average over many runs is 0.61 at N = 4 and 0.97 at N = 100. Measure: run at two sizes of N and compare. Fix: use more draws, and report the ESS with the answer.
Chapter 6
Shift the proposal onto the threshold, weight the hits, and find the best shift
Back to the tail of Chapter 0: P(X > 3) = 0.00135 for X from N(0,1). Shift the proposal to q = N(μ, 1), so many draws pass the threshold t = 3. Then weight each draw to undo the shift. This is exponential tilting, and it is the hero's sampler.
For this pair the weight has a closed form, because the √(2π) factors cancel. The estimate is the average of w(x) times 1{x > t}, a mark that is 1 if the draw passes t and 0 if not.
By hand, with μ = 3 and four draws 2.5, 3.2, 3.5, 4.0: the first misses, so its term is 0. The others give 0.00610, 0.00248 and 0.00055. The average is 0.00228. Four draws already reach the right order of magnitude.
Top: p, the tilted q and the rare region past t = 3. Bottom: relative error per draw against the shift, on a log scale. Slide the shift, then press Draw 1,000.
The curve is exact: relative variance per draw = eμ² · P(X > t + μ) / p² − 1. The draws are seeded.
The gain is precise. Per draw, the relative error is 27.2 for plain sampling and 1.84 at μ = 3. Square the ratio: one tilted draw is worth about 218 plain draws. The best shift is μ = 3.15, a little past t, where q* = 1{x > t}·p / Z piles its mass.
The failure. Symptom: the estimate wanders when q sits far past t. The few draws near t then carry huge weights. Measure: relative error per draw is 4.9 at μ = 5 and 16.3 at μ = 6. Fix: centre q at or just past the threshold.
Chapter 7
Score a new policy from another policy's logs, and watch the product of ratios explode with the horizon
A clinic logged months of decisions made under its current rule, the behavior policy b. You designed a new rule, the target policy π. What would π score, without trying it on patients? This is off-policy evaluation.
A logged episode is a list of states st and actions at. Its chance under a policy is a product: one action probability per step, times the environment's transition probabilities. The environment terms are the same under π and b, so they cancel in the ratio. Call the episode's total reward, the return, G.
V-hat equals G times the product over t of pi of a-t given s-t, over b of a-t given s-t.
At each step, divide the target's chance of the logged action by the behavior's chance. Multiply the ratios; call the product rho. Multiply rho by G. Average V-hat over many episodes.
On the logged actions, π gives 0.8, 0.5, 0.9 and b gives 0.4, 0.5, 0.3. The return is G = 2. Ratios 2, 1, 3, so rho = 6 and V̂ = 12. The target was six times as likely to produce this exact episode.
Why does length hurt? Take a toy with two actions. b picks each half the time; π picks one with chance 0.5 + m. Each step's ratio is 1 + 2m or 1 − 2m. Its mean is 1 and its mean square is 1 + 4m². Over H independent steps:
Purple bars count 4,000 episodes by their weight rho, on a log scale. The yellow line marks the mean, 1. Lengthen the episode or widen the gap and watch the mass slide left while a few episodes run far right.
The two-action toy above, simulated with a fixed seed. The variance in the read-out is exact.
The failure. Symptom: a few episodes decide the estimate. Measure: the share of total weight held by the top 1% of episodes. At m = 0.4 and H = 6 the median rho is 0.047 and the top 1% hold 34% of the weight. Fix: weighted IS (self-normalize the rho values, Chapter 5), and doubly robust estimators that add a learned value model (Jiang and Li, 2016).
The same ratio sits inside policy gradients and off-policy actor-critic, which reuse old data with clipped or truncated ratios.
Chapter 8
Pick light directions from the surface's reflection lobe and watch a noisy pixel go clean
You render a floor. Each pixel's brightness is an integral over every light direction on the half sphere above the point. The integrand is the incoming light L, times the surface's reflection function (the BRDF), times the cosine of the angle θ between the direction and the surface normal.
A path tracer estimates the integral one direction at a time with f/pdf: the integrand at a sampled direction, divided by the density that picked that direction. That is importance sampling, with q renamed pdf. For a matte surface under constant light, f = L·cos θ / π.
The cosine in the pdf cancels the cosine in the integrand. One sample gives the exact pixel. That is Chapter 3's q*: the pdf has the integrand's shape, so the ratio is constant.
Left: the half sphere, with sampled directions drawn as rays whose length is f/pdf. Right: a patch of pixels that should all be the same grey. Change the sampler, sharpen the lobe and set the samples per pixel.
A toy lobe: the integrand is proportional to cosk θ, aimed along the normal, scaled so the true pixel is 1. k = 1 is a matte surface. The noise figures are exact; the patch is a seeded simulation.
| Lobe | Uniform | Cosine | Lobe-matched |
|---|---|---|---|
| matte, k = 1 | 0.58 | 0 | 0 |
| glossy, k = 11 | 2.29 | 1.51 | 0 |
The table gives the relative error of one sample. With 16 samples per pixel, the glossy floor keeps 57% noise under uniform sampling and 38% under cosine sampling.
The failure. Symptom: grain and bright speckles that survive many samples. Measure: the standard deviation of one pixel across frames. Fix: sample from the BRDF lobe, and from the light sources too, then combine the two by multiple importance sampling (Veach, 1997).
Chapter 9
Replace one impossible reweighting with many small ones, and estimate a ratio of normalizers
Sometimes q and p barely overlap. One-step weights are either near 0 or huge, and the ESS stays near 1 for any number of draws. So build a ladder of in-between targets, from the easy start p0 to the hard target p̃1, and reweight one small step at a time. Radford Neal named this annealed importance sampling (AIS) in 2001.
The rungs are blends p̃β = p01−β · p̃1β, with β (beta) running from 0 to 1 over K rungs. A particle starts as a draw from p0. At each rung it picks up a small weight. Then an MCMC move (a random step that keeps the current blend as its target, see MCMC) carries it on. Call its position at rung k xk.
W equals the product over k of p-tilde beta-k of x-k, over p-tilde beta-k-minus-one of x-k.
At each rung, divide the next blend by the current blend at the particle's position x-k. Multiply that ratio into w. Then move the particle. The average w over many particles estimates Z1/Z0, the ratio of the two normalizers.
p0 = N(0,1) and p̃1 = exp(−x²/2 + μx), so each rung is N(βμ, 1) and each ratio is exp(Δβ · μ · xk). With μ = 1 and K = 2: start at 0.3, ratio e0.15 = 1.16; move to 0.9, ratio e0.45 = 1.57; w = 1.82. The truth, e0.5 = 1.65, is the average over many particles.
Top: the rungs from p0 (teal) to the target (pink). Bottom: the final weights of 48 particles, sorted. Widen the gap, then add rungs and watch the weights even out.
The move here is an ideal one: a fresh draw from each rung. Real AIS uses a few MCMC steps. The ESS and the estimate use 4,000 seeded particles; the bars show the first 48.
With ideal moves the log-weight has variance μ²/K, so ESS/N ≈ e−μ²/K. For μ = 3: 0.0001 with one rung, 0.41 with 10, 0.74 with 30.
The failure. Symptom: one particle holds most of the weight and Z1/Z0 comes out low. With μ = 3, one rung and 20,000 particles, a run gave 71.5 against a truth of 90.0. Measure: the ESS of the final weights. Fix: more rungs, better moves, or resampling between rungs, which is Sequential Monte Carlo.
Chapter 10
Keep the terms, the numbers, the checks and the code in one place
Draw from a q you can afford. Weight each draw by p/q. Shape q like p times |f|, keep its tails heavy, and read the ESS before you trust the answer. Every application on this page is that one move.
| Term | What it is | Number from this page |
|---|---|---|
| Weight w | p(x)/q(x) for one draw | w(2.5) = 0.050 for p = N(0,1), q = N(3,1) |
| Estimate μ̂ | average of w·f over draws from q | 1.15 from three draws, truth 1 |
| Variance σ²IS | ∫ p²f²/q dx − μ² | 2 for q = p; 0.49 for width 1.5; infinite below 0.707 |
| Optimal q* | |f|·p / Z | variance 0, but Z is the answer |
| ESS | (Σw)² / Σw² | 1.08 for weights 1, 1, 1, 1, 100 |
| SNIS | Σw̃f / Σw̃ | average 0.61 at N = 4, 0.97 at N = 100 |
| Tilting | q = N(μ, 1) for a tail | 218 times fewer draws at μ = 3 for P(X > 3) |
| Off-policy ρ | product of π/b over steps | Var = 1,023 at m = 0.5, H = 10 |
| BRDF sampling | pdf shaped like the lobe | matte: 0.58 to 0 per-sample error |
| AIS | a ladder of reweightings with moves | ESS/N 0.0001 to 0.74 with 30 rungs |
pythonimport numpy as np from scipy.stats import norm rng = np.random.default_rng(0) def importance_sample(f, log_p, log_q, sample_q, n): x = sample_q(n) # n draws from the proposal log_w = log_p(x) - log_q(x) # log weights: safer than p/q w = np.exp(log_w - log_w.max()) # rescale; SNIS cancels the shift ess = w.sum()**2 / (w**2).sum() snis = np.sum(w * f(x)) / w.sum() return snis, ess / n # tail P(X > 3) with an exact weight and a tilted proposal x = rng.normal(3.0, 1.0, 10_000) w = np.exp(4.5 - 3.0 * x) # p/q for p = N(0,1), q = N(3,1) print(np.mean(w * (x > 3)), norm.sf(3)) # 0.00128 vs 0.00135
Monte Carlo, averages of random draws, is the root of this family. MCMC draws from p itself with a chain, at the cost of correlated draws. Hamiltonian Monte Carlo makes those chain steps long and cheap. Sequential Monte Carlo adds resampling to the ladder of Chapter 9. Quasi-Monte Carlo replaces random draws with evenly spread points. Monte Carlo tree search uses rollouts to choose moves.
| Wall you hit | What it looks like | Where to go |
|---|---|---|
| Light-tailed q | one weight dominates; the mean jumps | widen q, imitate q* (Chapters 2, 3) |
| q and p barely overlap | ESS near 1 | AIS, then SMC |
| Long horizons | Var(ρ) grows like (1 + 4m²)H | weighted IS, doubly robust |
| You need draws from p | IS only reweights | MCMC |
Monte Carlo (the family hub) · MCMC · Sequential Monte Carlo · Policy gradients · Off-policy actor-critic · NEU 560: Monte Carlo and importance sampling
Further reading: Art Owen, Monte Carlo theory, methods and examples, chapter 9.
Radford Neal, "Annealed Importance Sampling" (arXiv, 2001); Precup, Sutton and Singh, "Eligibility Traces for Off-Policy Policy Evaluation" (2000); Eric Veach, PhD thesis on robust Monte Carlo light transport (Stanford, 1997).
Now press Present or Teach and explain from memory: the weight, why the answer stays exact, where the variance comes from, and how ESS warns you. Then go back to the hero and estimate the tail at t = 6 both ways. Say why one sampler reports zero and the other lands within a few percent.