Type at least 2 letters. Enter opens the first result, Esc closes.

    Probability and Statistics · Lesson 14 · Monte Carlo and MCMC

    Monte Carlo: rejection sampling, importance sampling and variance reduction

    Intermediate 75 min 5 interactive figures 3 videos Colab notebook

    Before this lesson: lesson 02 (expectation and inverse-CDF sampling), lesson 03 (the exponential and normal distributions), lesson 06 (the law of large numbers, the CLT and the Monte Carlo error bar), lesson 10 (posteriors known only up to a constant). From foundations: log-sum-exp. Time: about 75 minutes, plus the notebook.


    Why this matters #

    • Expectations everywhere. A Bayesian prediction is Ep(θ∣D)[p(y∣θ)]\mathbb{E}_{p(\theta \mid \mathcal D)}[p(y \mid \theta)]; a VAE trains on a Monte Carlo estimate of the ELBO; a policy gradient is a Monte Carlo average over trajectories.
    • Importance weights in modern ML. PPO's probability ratio, off-policy evaluation in reinforcement learning, the IWAE bound and particle filters are all importance sampling. Speculative decoding in LLM serving is a form of rejection sampling.
    • Rare events in science and engineering. The probability that a flood, an earthquake or a structural load exceeds a design level is tiny. Plain sampling needs about 100/μ100/\mu draws for 10% accuracy on an event of probability μ\mu; importance sampling can cut this by orders of magnitude.
    • The bridge to MCMC. When no good proposal exists (high dimension, complex posterior), Markov chain Monte Carlo takes over (lesson 15). Its error bars use the same ideas as here.

    1. Predict first #

    2. The picture #

    Estimate π\pi with darts. Throw nn points uniformly into the square [−1,1]2[-1, 1]^2 and count the fraction inside the unit disk. The disk covers π/4\pi/4 of the square, so 4×4 \times (fraction inside) estimates π\pi. Each dart is a coin flip with P(inside)=π/4P(\text{inside}) = \pi/4, so the estimate has standard error 4(π/4)(1−π/4)/n≈1.64/n4\sqrt{(\pi/4)(1 - \pi/4)/n} \approx 1.64/\sqrt n.

    Interactive figure: loading…

    Press "+1,000" a few times, then "Play". Darts inside the disk are aqua, outside magenta. The blue path is the running estimate π^n\hat\pi_n; the orange lines are π\pi and the band π±2 SE⁡\pi \pm 2\,\operatorname{SE}. Switch the view to "error": on log–log axes the error follows a line of slope −1/2-1/2. Try "New seed": every path stays mostly inside the band.

    The error formula has three levers. The standard error of an average of nn i.i.d. draws of f(X)f(X) is σf/n\sigma_f/\sqrt n, where σf\sigma_f is the standard deviation of f(X)f(X). To make it smaller you can:

    • take more samples. This is slow: 4 times the work buys 2 times the accuracy.
    • sample from somewhere else. Draw from a proposal qq that puts points where they matter, and correct with weights w=p/qw = p/q (importance sampling).
    • make the integrand less variable. Subtract a correlated quantity with a known mean (control variates), or pair each draw with a mirrored twin (antithetic variables).

    Weights correct the bias. Suppose the target is p=N(0,1)p = \mathcal N(0, 1) but we draw from a wider qq. Points far out are over-represented, so they get a small weight p(x)/q(x)p(x)/q(x); points near 0 are under-represented and get a weight above 1. The weighted average is then correct on average. But if qq is narrower than pp, a rare draw in the tail gets an enormous weight and dominates the whole average.

    Interactive figure: loading…

    Try the four presets, and press "New seed" several times for each. The target pp is orange and the proposal qq is violet. The lower plot shows the normalised weight of each of the 200 draws as a blue stick; the largest is yellow, and the dashed line is the equal weight 1/n1/n. The effective sample size (ESS) says how many equally weighted draws the weighted sample is worth. With the "too narrow" proposal, most runs look calm, and then one draw takes most of the weight.

    Quick check

    You estimate π\pi with n=10,000n = 10{,}000 darts. About how large is the standard error, and how many darts do you need to make it 10 times smaller?

    3. Definitions and main results #

    Simple Monte Carlo (recap of lesson 06) #

    We want μ=Ep[f(X)]=∫f(x) p(x) dx\mu = \mathbb{E}_p[f(X)] = \int f(x)\,p(x)\,dx. Draw X1,…,XnX_1, \dots, X_n i.i.d. from pp and set

    μ^n=1n∑i=1nf(Xi).\hat\mu_n = \frac1n\sum_{i=1}^n f(X_i) .

    Then E[μ^n]=μ\mathbb{E}[\hat\mu_n] = \mu and Var⁡(μ^n)=σf2/n\operatorname{Var}(\hat\mu_n) = \sigma_f^2/n with σf2=Var⁡p(f(X))\sigma_f^2 = \operatorname{Var}_p(f(X)). The law of large numbers gives μ^n→μ\hat\mu_n \to \mu, and the CLT gives the error bar μ^n±1.96 sf/n\hat\mu_n \pm 1.96\,s_f/\sqrt n, where sfs_f is the sample standard deviation of the f(Xi)f(X_i) (lesson 06).

    Rare events. For a probability μ=P(A)\mu = P(A), take f=1Af = \mathbf 1_A. Then σf2=μ(1−μ)\sigma_f^2 = \mu(1 - \mu) and the relative standard error is

    μ(1−μ)/nμ=1−μnμ≈1nμ.\frac{\sqrt{\mu(1 - \mu)/n}}{\mu} = \sqrt{\frac{1 - \mu}{n\mu}} \approx \frac{1}{\sqrt{n\mu}} .

    Here nμn\mu is the expected number of hits. For 10% relative error you need about 100 hits, so about 100/μ100/\mu draws. The error depends on how many times you see the event, not on nn alone.

    Exact samplers: inverse CDF and rejection #

    Importance sampling is easier to understand after two methods that produce exact draws.

    Inverse CDF (lesson 02). If U∼Uniform(0,1)U \sim \text{Uniform}(0, 1) and FF is a CDF, then F−1(U)F^{-1}(U) has CDF FF (with the generalised inverse F−1(u)=inf⁡{x:F(x)≥u}F^{-1}(u) = \inf\{x : F(x) \ge u\} for steps and flat parts). For the exponential with rate λ\lambda, x=−log⁡(1−u)/λx = -\log(1 - u)/\lambda. It needs a CDF you can invert; the Gaussian has none in closed form (use Box–Muller, lesson 05, or a numerical inverse).

    Rejection sampling. Often you can evaluate the target only up to a constant: p=p~/Zp = \tilde p/Z, where you know p~\tilde p but not Z=∫p~Z = \int\tilde p. A posterior is the typical case: likelihood times prior is p~\tilde p, and ZZ is the evidence (lesson 10). Choose a proposal density qq that you can sample, and a constant MM with an envelope: p~(x)≤Mq(x)\tilde p(x) \le M q(x) for all xx.

    Algorithm: draw X∼qX \sim q and U∼Uniform(0,1)U \sim \text{Uniform}(0, 1) independently. Accept XX if U≤p~(X)/(Mq(X))U \le \tilde p(X)/(Mq(X)); otherwise try again.

    Picture: the points (X,U Mq(X))(X, U\,Mq(X)) are uniform under the graph of MqMq. We keep the ones under the graph of p~\tilde p. Those are uniform under p~\tilde p, so their xx-coordinate has density proportional to p~\tilde p.

    Theorem (rejection sampling is exact). An accepted XX has density pp. Each trial is accepted with probability Z/MZ/M, so the number of trials per accepted sample is geometric with mean M/ZM/Z.

    Proof.

    1. Given X=xX = x, the acceptance probability is p~(x)/(Mq(x))\tilde p(x)/(Mq(x)), a number in [0,1][0, 1] because of the envelope.
    2. For a set AA: P(X∈A, accept)=∫Aq(x) p~(x)Mq(x) dx=1M∫Ap~(x) dxP(X \in A,\ \text{accept}) = \int_A q(x)\,\frac{\tilde p(x)}{Mq(x)}\,dx = \frac1M\int_A \tilde p(x)\,dx.
    3. Take AA = everything: P(accept)=Z/MP(\text{accept}) = Z/M.
    4. Divide: P(X∈A∣accept)=(1/M)∫Ap~Z/M=∫Ap(x) dxP(X \in A \mid \text{accept}) = \frac{(1/M)\int_A\tilde p}{Z/M} = \int_A p(x)\,dx. So the accepted XX has density pp.
    5. Trials are i.i.d. with success probability Z/MZ/M, so their number is geometric with mean M/ZM/Z. ■\blacksquare

    Use the smallest valid M=sup⁡xp~(x)/q(x)M = \sup_x \tilde p(x)/q(x). The supremum must be finite, so qq must have tails at least as heavy as p~\tilde p: a Gaussian proposal can never envelope a Cauchy target. If MM is too small, the envelope dips below p~\tilde p and the samples are silently wrong there. A too large MM is only slow.

    Interactive figure: loading…

    Press "+500", then move MM below 1.65. The target p~(x)=e−x2/2\tilde p(x) = e^{-x^2/2} (x≥0x \ge 0) is orange, the envelope Me−xM e^{-x} is violet. Proposals under p~\tilde p are accepted (aqua), the others rejected (magenta); "Step" shows one proposal in yellow. The histogram compares the accepted samples with the target density. Below M=e≈1.649M = \sqrt e \approx 1.649 a magenta region appears where the envelope is too low, and the histogram misses mass near x=1x = 1.

    High dimension kills rejection. For the target N(0,Id)\mathcal N(0, I_d) and the proposal N(0,s2Id)\mathcal N(0, s^2 I_d) with s>1s > 1, the ratio p/qp/q is largest at x=0x = 0, so M=sdM = s^d and the acceptance rate is s−ds^{-d}. With s=1.1s = 1.1 and d=100d = 100 it is 7⋅10−57 \cdot 10^{-5}. Rejection sampling is a tool for low dimension.

    Importance sampling #

    Importance sampling keeps every draw from qq and fixes the bias with weights.

    The identity. If q(x)>0q(x) > 0 wherever f(x)p(x)≠0f(x)p(x) \ne 0, then with the importance weight w(x)=p(x)/q(x)w(x) = p(x)/q(x),

    μ=∫f(x) p(x) dx=∫f(x) p(x)q(x) q(x) dx=Eq[f(X) w(X)].\mu = \int f(x)\,p(x)\,dx = \int f(x)\,\frac{p(x)}{q(x)}\,q(x)\,dx = \mathbb{E}_q\big[f(X)\,w(X)\big].

    Estimator. Draw X1,…,XnX_1, \dots, X_n i.i.d. from qq and set μ^q=1n∑iw(Xi)f(Xi)\hat\mu_q = \frac1n\sum_i w(X_i) f(X_i). It is unbiased by the identity. It is an average of i.i.d. terms, so

    Var⁡(μ^q)=σq2n,σq2=Eq[w2f2]−μ2=∫f(x)2p(x)2q(x) dx−μ2.\operatorname{Var}(\hat\mu_q) = \frac{\sigma_q^2}{n}, \qquad \sigma_q^2 = \mathbb{E}_q[w^2 f^2] - \mu^2 = \int \frac{f(x)^2 p(x)^2}{q(x)}\,dx - \mu^2 .

    Estimate the standard error by the sample standard deviation of the terms w(Xi)f(Xi)w(X_i)f(X_i), divided by n\sqrt n.

    The best proposal. q∗∝∣f∣ pq^* \propto |f|\,p minimises σq2\sigma_q^2.

    1. Only Eq[w2f2]\mathbb{E}_q[w^2 f^2] depends on qq.
    2. By Jensen (or Cauchy–Schwarz), Eq[w2f2]≥(Eq[w∣f∣])2=(Ep∣f∣)2\mathbb{E}_q[w^2 f^2] \ge \big(\mathbb{E}_q[w|f|]\big)^2 = \big(\mathbb{E}_p|f|\big)^2 for every qq.
    3. Equality holds when w∣f∣w|f| is constant, that is when q∝∣f∣ pq \propto |f|\,p. ■\blacksquare

    For f≥0f \ge 0 the best proposal q∗=fp/μq^* = fp/\mu gives zero variance, but it needs the unknown μ\mu. The practical lesson: put the proposal where ∣f∣ p|f|\,p is large. For the rare event {X>a}\{X > a\}, that region is just above aa, so shift the proposal there.

    Interactive figure: loading…

    Press "Run again" several times, then move the threshold aa. The chart shows running estimates divided by the true value, so the target is the orange line at 1. Plain Monte Carlo (blue) is 0 until its first hit, then jumps. Importance sampling with q=N(a,1)q = \mathcal N(a, 1) (aqua) settles near 1 after a few hundred draws. Dashed lines are 1±21 \pm 2 relative standard errors from the theory. At a=4a = 4 the variance ratio is about 7,000.

    Why the proposal needs heavier tails. Take p=N(0,1)p = \mathcal N(0, 1) and q=N(0,s2)q = \mathcal N(0, s^2). Then w(x)=sexp⁡ ⁣(−x22(1−s−2))w(x) = s\exp\!\big(-\tfrac{x^2}{2}(1 - s^{-2})\big) and

    Eq[w2]=∫p2q dx=s22s2−1if s2>12,and +∞ if s2≤12.\mathbb{E}_q[w^2] = \int\frac{p^2}{q}\,dx = \frac{s^2}{\sqrt{2s^2 - 1}} \quad\text{if } s^2 > \tfrac12, \qquad\text{and } +\infty \text{ if } s^2 \le \tfrac12 .

    When s<1s < 1, the weight grows without bound in the tails: qq rarely visits them, and a visit gets a huge weight. A heavier-tailed qq (s>1s > 1) has bounded weights, w≤sw \le s. In general the condition is ∫f2p2/q<∞\int f^2 p^2/q < \infty.

    Infinite variance is a silent failure. The estimator stays unbiased, and it still converges (the strong law of large numbers needs only Eq∣wf∣<∞\mathbb{E}_q|wf| < \infty). But there is no CLT error bar, and the sample standard error is itself unreliable. Most runs miss the tail and look stable; for f≥0f \ge 0 they are usually too small. A rare run jumps.

    Quick check

    For p=N(0,1)p = \mathcal N(0, 1) you can choose the proposal q=N(0,s2)q = \mathcal N(0, s^2). For which ss is the variance of the importance weights finite?

    Self-normalised importance sampling #

    Often you know only p~=Zp\tilde p = Zp. Use unnormalised weights wi=p~(xi)/q(xi)w_i = \tilde p(x_i)/q(x_i) and

    μ~=∑iwif(xi)∑iwi=∑iwˉif(xi),wˉi=wi∑jwj,Z^=1n∑iwi.\tilde\mu = \frac{\sum_i w_i f(x_i)}{\sum_i w_i} = \sum_i \bar w_i f(x_i), \qquad \bar w_i = \frac{w_i}{\sum_j w_j}, \qquad \hat Z = \frac1n\sum_i w_i .

    This is self-normalised importance sampling (SNIS).

    • Z^\hat Z is unbiased for ZZ, because Eq[p~/q]=∫p~=Z\mathbb{E}_q[\tilde p/q] = \int\tilde p = Z. For a Bayesian model this is the evidence p(D)p(\mathcal D). Its log is biased low: E[log⁡Z^]≤log⁡Z\mathbb{E}[\log\hat Z] \le \log Z by Jensen.
    • μ~\tilde\mu is consistent: the numerator over nn tends to ZμZ\mu and the denominator over nn to ZZ.
    • μ~\tilde\mu is biased, because E[A/B]≠E[A]/E[B]\mathbb{E}[A/B] \ne \mathbb{E}[A]/\mathbb{E}[B]. With n=1n = 1, μ~=f(X1)\tilde\mu = f(X_1) with X1∼qX_1 \sim q, so E[μ~]=Eq[f]\mathbb{E}[\tilde\mu] = \mathbb{E}_q[f], not Ep[f]\mathbb{E}_p[f]. The bias is O(1/n)O(1/n), small next to the standard error O(1/n)O(1/\sqrt n).
    • Its variance is approximately 1nEq[w2(f−μ)2]\frac1n\mathbb{E}_q\big[w^2(f - \mu)^2\big] (normalised w=p/qw = p/q; delta method). Estimate it with ∑iwˉi2(f(xi)−μ~)2\sum_i\bar w_i^2\big(f(x_i) - \tilde\mu\big)^2.
    • Numerics. Work with log-weights ℓi=log⁡p~(xi)−log⁡q(xi)\ell_i = \log\tilde p(x_i) - \log q(x_i) and compute wˉi=exp⁡(ℓi−LSE⁡(ℓ))\bar w_i = \exp\big(\ell_i - \operatorname{LSE}(\ell)\big) with LSE⁡(ℓ)=m+log⁡∑ieℓi−m\operatorname{LSE}(\ell) = m + \log\sum_i e^{\ell_i - m}, m=max⁡iℓim = \max_i\ell_i (log-sum-exp). Raw weights overflow or underflow.

    The effective sample size #

    Definition (Kish). ne=(∑iwi)2∑iwi2=1∑iwˉi2∈[1,n].\displaystyle n_e = \frac{\big(\sum_i w_i\big)^2}{\sum_i w_i^2} = \frac{1}{\sum_i \bar w_i^2} \in [1, n].

    Where it comes from. Take i.i.d. YiY_i with variance σ2\sigma^2 and fixed weights. The weighted mean ∑iwiYi/∑iwi\sum_i w_iY_i/\sum_i w_i has variance σ2∑iwi2/(∑iwi)2\sigma^2\sum_i w_i^2/(\sum_i w_i)^2. An unweighted mean of nen_e draws has variance σ2/ne\sigma^2/n_e. Set the two equal and solve for nen_e.

    Properties. ne=nn_e = n for equal weights, and ne→1n_e \to 1 when one weight dominates. Scaling all weights by a constant does not change it, so p~\tilde p is enough. Its population version is n/Eq[w2]n/\mathbb{E}_q[w^2] (normalised ww). For p=N(0,1)p = \mathcal N(0, 1) and q=N(0,22)q = \mathcal N(0, 2^2) this is n7/4≈0.661 nn\sqrt 7/4 \approx 0.661\,n.

    The curse of dimension. For p=N(0,Id)p = \mathcal N(0, I_d) and q=N(m,Id)q = \mathcal N(m, I_d) one finds Eq[w2]=e∥m∥2\mathbb{E}_q[w^2] = e^{\|m\|^2}, so the population ESS is n e−∥m∥2n\,e^{-\|m\|^2}. A shift of 0.1 standard deviations in each of d=1000d = 1000 coordinates gives ∥m∥2=10\|m\|^2 = 10 and an ESS of 4.5⋅10−5 n4.5 \cdot 10^{-5}\,n. Small mismatches multiply over coordinates, and the weights collapse onto one draw.

    A diagnostic, not a guarantee. The ESS uses only the weights, not ff. A small ESS proves a problem. A large ESS does not prove success: if qq misses a mode of pp entirely, all draws can have similar weights and the estimate is still wrong.

    Quick check

    Five draws have importance weights (1,1,1,1,4)(1, 1, 1, 1, 4). What is the effective sample size?

    Variance reduction #

    Control variates. Let gg be a function with a known mean γ=E[g(X)]\gamma = \mathbb{E}[g(X)]. For any constant β\beta,

    μ^β=1n∑i[f(Xi)−β(g(Xi)−γ)]\hat\mu_\beta = \frac1n\sum_i\Big[f(X_i) - \beta\big(g(X_i) - \gamma\big)\Big]

    is unbiased, because the subtracted term has mean 0.

    1. Its variance is 1n(σf2−2βCov⁡(f,g)+β2σg2)\frac1n\big(\sigma_f^2 - 2\beta\operatorname{Cov}(f, g) + \beta^2\sigma_g^2\big), a parabola in β\beta.
    2. Set the derivative to zero: β∗=Cov⁡(f,g)/Var⁡(g)\beta^* = \operatorname{Cov}(f, g)/\operatorname{Var}(g), the least-squares slope of ff on gg.
    3. Substitute: the minimum is (1−ρ2) σf2/n(1 - \rho^2)\,\sigma_f^2/n, where ρ=Corr⁡(f,g)\rho = \operatorname{Corr}(f, g). ■\blacksquare

    With ρ=0.9\rho = 0.9 the variance falls to 19%; the sign of ρ\rho does not matter. In practice β\beta is estimated from the same draws, which adds a bias of order 1/n1/n. It helps when gg is cheap, strongly correlated with ff, and has an exactly known mean. This is the same idea as CUPED in A/B testing, where a pre-experiment metric is the control (lesson 12), and as the baseline in a policy gradient.

    Antithetic variables. Pair each uniform UU with 1−U1 - U (or a Gaussian ε\varepsilon with −ε-\varepsilon). With nn evaluations of hh, use n/2n/2 pairs and average Yj=12(h(Uj)+h(1−Uj))Y_j = \frac12\big(h(U_j) + h(1 - U_j)\big).

    1. Var⁡(Yj)=14(σ2+σ2+2ρσ2)=σ22(1+ρ)\operatorname{Var}(Y_j) = \frac14\big(\sigma^2 + \sigma^2 + 2\rho\sigma^2\big) = \frac{\sigma^2}{2}(1 + \rho), with ρ=Corr⁡(h(U),h(1−U))\rho = \operatorname{Corr}\big(h(U), h(1 - U)\big).
    2. So the estimator has variance σ2(1+ρ)/2n/2=σ2(1+ρ)/n\frac{\sigma^2(1 + \rho)/2}{n/2} = \sigma^2(1 + \rho)/n, against σ2/n\sigma^2/n for nn independent draws.
    3. It helps exactly when ρ<0\rho < 0. ■\blacksquare

    If hh is monotone, h(U)h(U) and h(1−U)h(1 - U) move in opposite directions, so ρ≤0\rho \le 0 and antithetics never hurt. If h(u)=h(1−u)h(u) = h(1 - u) (symmetric about 12\frac12), then ρ=1\rho = 1 and the variance doubles. If hh is linear, the variance is 0.

    Interactive figure: loading…

    Move the slider β\beta to the bottom of the parabola, then switch "Antithetic pairs" on. The problem is ln⁡2=E[1/(1+U)]\ln 2 = \mathbb{E}[1/(1 + U)] with the control g(U)=Ug(U) = U. Top: draws (u,h(u))(u, h(u)) in blue, the line with slope β\beta in yellow, the least-squares slope β∗\beta^* dashed in orange. Bottom: the variance factor of the control-variate estimator as a function of β\beta; its minimum 1−ρ21 - \rho^2 is at β∗\beta^*. The aqua line is the antithetic factor 1+ρ1 + \rho. Then try h(u)=(u−12)2h(u) = (u - \frac12)^2: the control is useless and the antithetic pairs double the variance. "Check by simulation" measures both factors.

    Answers to section 1. (1) About 50%. The expected number of hits is nμ≈3.2n\mu \approx 3.2, so the relative standard error is (1−μ)/(nμ)≈0.56\sqrt{(1 - \mu)/(n\mu)} \approx 0.56. With probability e−3.2≈0.04e^{-3.2} \approx 0.04 there is no hit at all. (2) Proposal A. Its variance is s2=0.25<1/2s^2 = 0.25 < 1/2, so Eq[w2]=∞\mathbb{E}_q[w^2] = \infty: the estimate is unbiased but has infinite variance. Proposal B has bounded weights w≤2w \le 2 and an ESS of about 0.661 n0.661\,n.

    4. Worked example #

    (a) Rejection: a half-normal from an exponential. Target p~(x)=e−x2/2\tilde p(x) = e^{-x^2/2} on [0,∞)[0, \infty), with Z=π/2=1.2533Z = \sqrt{\pi/2} = 1.2533. Proposal q(x)=e−xq(x) = e^{-x} (Exponential(1)).

    • p~/q=ex−x2/2\tilde p/q = e^{x - x^2/2}. Its exponent x−x2/2x - x^2/2 has derivative 1−x1 - x, so the maximum is at x=1x = 1: M=e1/2=1.6487M = e^{1/2} = 1.6487.
    • Accept xx with probability p~(x)/(Mq(x))=e−x2/2+x−1/2=e−(x−1)2/2\tilde p(x)/(Mq(x)) = e^{-x^2/2 + x - 1/2} = e^{-(x - 1)^2/2}.
    • Acceptance rate Z/M=1.2533/1.6487=0.760Z/M = 1.2533/1.6487 = 0.760; on average 1/0.760=1.321/0.760 = 1.32 proposals per sample.
    • Proposal x=0.5x = 0.5 with u=0.6u = 0.6: e−0.125=0.882>0.6e^{-0.125} = 0.882 > 0.6, accept. Proposal x=2.5x = 2.5 with u=0.6u = 0.6: e−1.125=0.325<0.6e^{-1.125} = 0.325 < 0.6, reject.

    (b) Importance sampling by hand. Target p=N(0,1)p = \mathcal N(0, 1), proposal q=N(0,22)q = \mathcal N(0, 2^2), f(x)=x2f(x) = x^2 (true value 1). Then w(x)=p(x)/q(x)=e−x2/2/2πe−x2/8/(22π)=2e−3x2/8w(x) = p(x)/q(x) = \frac{e^{-x^2/2}/\sqrt{2\pi}}{e^{-x^2/8}/(2\sqrt{2\pi})} = 2e^{-3x^2/8}. Four draws from qq:

    xix_i −2-2 00 11 33
    wiw_i 0.446 2.000 1.375 0.068
    wif(xi)w_i f(x_i) 1.785 0 1.375 0.616
    • Plain IS: 14(1.785+0+1.375+0.616)=0.944\frac14(1.785 + 0 + 1.375 + 0.616) = 0.944.
    • SNIS: ∑wi=3.889\sum w_i = 3.889, so μ~=3.776/3.889=0.971\tilde\mu = 3.776/3.889 = 0.971; and Z^=3.889/4=0.972\hat Z = 3.889/4 = 0.972 (true Z=1Z = 1).
    • ESS: ∑wi2=6.093\sum w_i^2 = 6.093, so ne=3.8892/6.093=2.48n_e = 3.889^2/6.093 = 2.48 of 4 draws. The draw at 0 alone carries 51% of the normalised weight.

    (c) A rare event. μ=P(X>4)=3.167⋅10−5\mu = P(X > 4) = 3.167 \cdot 10^{-5} for X∼p=N(0,1)X \sim p = \mathcal N(0, 1), f(x)=1{x>4}f(x) = \mathbf 1\{x > 4\}. Proposal q=N(4,1)q = \mathcal N(4, 1).

    • The weight: log⁡p(x)−log⁡q(x)=−x22+(x−4)22=−4x+8\log p(x) - \log q(x) = -\frac{x^2}{2} + \frac{(x - 4)^2}{2} = -4x + 8, so w(x)=e−4x+8w(x) = e^{-4x + 8}. On the event it is small: w(4)=e−8=3.4⋅10−4w(4) = e^{-8} = 3.4 \cdot 10^{-4}.
    • Second moment: Eq[w2f]=Ep[wf]=∫4∞e−4x+8φ(x) dx\mathbb{E}_q[w^2 f] = \mathbb{E}_p[wf] = \int_4^\infty e^{-4x + 8}\varphi(x)\,dx, where φ\varphi is the standard normal density. Complete the square: e−4xφ(x)=e8φ(x+4)e^{-4x}\varphi(x) = e^{8}\varphi(x + 4), so the integral is e16P(X>8)=5.53⋅10−9e^{16}P(X > 8) = 5.53 \cdot 10^{-9}.
    • Variance per draw: IS 5.53⋅10−9−μ2=4.52⋅10−95.53 \cdot 10^{-9} - \mu^2 = 4.52 \cdot 10^{-9}; plain MC μ(1−μ)=3.17⋅10−5\mu(1 - \mu) = 3.17 \cdot 10^{-5}.
    • Ratio about 7,000. With n=105n = 10^5, the relative standard error falls from 0.56 to 0.0067.

    (d) Variance reduction for ln⁡2=E[11+U]\ln 2 = \mathbb{E}\big[\frac{1}{1 + U}\big]. Let h(u)=1/(1+u)h(u) = 1/(1 + u).

    • E[h2]=∫01(1+u)−2du=12\mathbb{E}[h^2] = \int_0^1 (1 + u)^{-2}du = \frac12, so Var⁡(h(U))=12−(ln⁡2)2=0.01955\operatorname{Var}(h(U)) = \frac12 - (\ln 2)^2 = 0.01955.
    • Control g(U)=Ug(U) = U (mean 12\frac12, variance 112\frac1{12}). E[Uh(U)]=∫01u1+udu=1−ln⁡2\mathbb{E}[Uh(U)] = \int_0^1\frac{u}{1 + u}du = 1 - \ln 2, so Cov⁡(h,U)=(1−ln⁡2)−ln⁡22=−0.0397\operatorname{Cov}(h, U) = (1 - \ln 2) - \frac{\ln 2}{2} = -0.0397. Then β∗=−0.0397⋅12=−0.477\beta^* = -0.0397 \cdot 12 = -0.477 and ρ2=0.039720.01955/12=0.969\rho^2 = \frac{0.0397^2}{0.01955/12} = 0.969. The variance falls by the factor 0.031: about 32 times fewer draws.
    • Antithetic: E[h(U)h(1−U)]=∫01du(1+u)(2−u)=23ln⁡2\mathbb{E}[h(U)h(1 - U)] = \int_0^1\frac{du}{(1 + u)(2 - u)} = \frac23\ln 2, so Cov⁡=23ln⁡2−(ln⁡2)2=−0.0184\operatorname{Cov} = \frac23\ln 2 - (\ln 2)^2 = -0.0184 and ρ=−0.939\rho = -0.939. The factor is 1+ρ=0.0611 + \rho = 0.061: about 16 times fewer evaluations. hh is monotone, so ρ<0\rho < 0 was guaranteed.
    Quick check

    You use antithetic pairs (U,1−U)(U, 1 - U) to estimate E[h(U)]\mathbb{E}[h(U)] for h(u)=(u−12)2h(u) = (u - \frac12)^2. Compared with the same number of independent evaluations, the variance of the estimate is

    5. In code #

    The notebook asks you to write the samplers and estimators yourself. Here NumPy and SciPy check the numbers of sections 3 and 4 by simulation, with n=105n = 10^5 draws each.

    import numpy as np
    from scipy import stats
    
    rng = np.random.default_rng(0)
    n = 100_000
    
    # Simple Monte Carlo: pi with a CLT error bar
    u = rng.uniform(-1, 1, size=(n, 2))
    f = 4 * (np.sum(u**2, axis=1) <= 1)
    print(f"{f.mean():.4f} +- {2 * f.std(ddof=1) / np.sqrt(n):.4f}")            # 3.1471 +- 0.0104
    
    # Rejection: half-normal target exp(-x^2/2) on [0, inf), Exp(1) proposal, M = e^{1/2}
    x = rng.exponential(size=n)
    keep = rng.uniform(size=n) <= np.exp(-(x - 1)**2 / 2)                     # p~ / (M q)
    print(round(keep.mean(), 3), round(stats.kstest(x[keep], stats.halfnorm.cdf).pvalue, 2))   # 0.757 0.62
    
    # Importance sampling for P(X > 4) with q = N(4, 1)
    mu = stats.norm.sf(4)
    plain = (rng.standard_normal(n) > 4).astype(float)
    xq = 4 + rng.standard_normal(n)
    wf = np.exp(-4 * xq + 8) * (xq > 4)                                       # w = p/q times the indicator
    for name, v in [("plain", plain), ("IS", wf)]:
        print(name, f"{v.mean():.3e} rel. SE {v.std(ddof=1) / np.sqrt(n) / mu:.4f}")
    print(f"exact {mu:.3e}")
    # plain 5.000e-05 rel. SE 0.7060      (5 hits)
    # IS 3.176e-05 rel. SE 0.0067
    # exact 3.167e-05
    
    # Self-normalised IS with log-weights: E[X^2] = 1 under p = N(0, 1), q = N(0, 2^2)
    xs = 2 * rng.standard_normal(n)
    logw = stats.norm.logpdf(xs) - stats.norm.logpdf(xs, scale=2)
    wbar = np.exp(logw - logw.max()); wbar /= wbar.sum()
    print(round(np.sum(wbar * xs**2), 3), round(1 / np.sum(wbar**2) / n, 3))   # 0.997 0.661
    
    # Control variate and antithetic pairs for ln 2 = E[1/(1+U)], same number of evaluations
    U = rng.uniform(size=n)
    h = 1 / (1 + U)
    beta = np.cov(h, U)[0, 1] / np.var(U, ddof=1)
    cv = h - beta * (U - 0.5)
    anti = 0.5 * (1 / (1 + U[: n // 2]) + 1 / (2 - U[: n // 2]))             # n/2 pairs = n evaluations
    print(round(beta, 3), round(cv.var() / h.var(), 3), round(2 * anti.var() / h.var(), 3))   # -0.477 0.031 0.061
    

    In this run plain Monte Carlo saw 5 hits instead of the expected 3.2, so its estimate is 58% too high; its sample standard error is itself noisy. Importance sampling is within 0.3% of the exact value.

    6. Where it shows up #

    • Speculative decoding in LLMs (ml-systems 12). A small draft model proposes a token x∼qx \sim q; the large model accepts it with probability min⁡(1,p(x)/q(x))\min(1, p(x)/q(x)). On rejection it samples once from the normalised residual max⁡(0,p−q)\max(0, p - q). The accepted part has mass min⁡(p,q)\min(p, q) and the residual part max⁡(0,p−q)\max(0, p - q); they add up to pp, so the output distribution is exactly the large model's.
    • Importance weights in reinforcement learning. Off-policy evaluation reweights returns by π(a∣s)/μ(a∣s)\pi(a \mid s)/\mu(a \mid s) (RL 04). PPO's probability ratio is an importance weight that is clipped to control its variance (RL 09).
    • Variational inference. The IWAE bound E[log⁡1K∑kwk]\mathbb{E}\big[\log\frac1K\sum_k w_k\big] is E[log⁡Z^]\mathbb{E}[\log\hat Z] with KK draws from the encoder: biased low by Jensen, and tighter as KK grows (generative models 01).
    • Particle filters and data assimilation. A particle filter is sequential SNIS: weight the ensemble members by the likelihood of new observations, and resample when the ESS drops (a common rule is ne<n/2n_e < n/2). In high-dimensional weather models the weights collapse onto one member unless the ensemble grows exponentially with the effective dimension. This is one reason weather centres use ensemble Kalman and variational methods instead (ml-for-science 06).
    • Rare events in science. Seismic hazard (the probability that ground motion at a site exceeds a design level), extreme rainfall, failure of a structure. A proposal shifted toward the event, as in (c), cuts the cost by orders of magnitude.
    • Control variates. The baseline in REINFORCE (RL 07, calculus 12). Multi-fidelity Monte Carlo uses a cheap emulator, whose mean is known from many cheap runs, as the control for an expensive simulator.
    • Antithetic sampling. Mirrored noise (ε,−ε)(\varepsilon, -\varepsilon) in evolution strategies and in finite-difference gradient estimators.

    7. Common mistakes #

    • A proposal with lighter tails than the target. The weights have infinite variance; the estimate looks stable for many runs and then jumps. Check ∫f2p2/q<∞\int f^2p^2/q < \infty, or use a heavy-tailed proposal (a Student tt, a wider Gaussian, or a mixture with a broad component).
    • Forgetting the support condition. If q=0q = 0 where fp≠0fp \ne 0, plain IS is biased. SNIS needs q>0q > 0 wherever p>0p > 0.
    • Weights in linear space. p~(x)/q(x)\tilde p(x)/q(x) overflows or underflows in high dimension. Use log-weights and log-sum-exp.
    • Trusting a large ESS. It cannot see a mode that no draw visited.
    • Using the plain-IS standard error for SNIS. Use ∑iwˉi2(f(xi)−μ~)2\sum_i\bar w_i^2(f(x_i) - \tilde\mu)^2, not the sample variance of wif(xi)w_if(x_i).
    • A rejection envelope that is too low. If p~>Mq\tilde p > Mq somewhere, the samples are silently wrong there. A too high MM is only slow.
    • Reporting a rare-event estimate with too few hits. With 3 expected hits, the estimate is often 0 or off by a factor 2. Count the hits; aim for at least 100, or use importance sampling.
    • Antithetic pairs for a symmetric integrand. For h(u)=h(1−u)h(u) = h(1 - u) they double the variance.
    • A control variate whose mean is only estimated. The error of that estimate adds directly to the error of μ^β\hat\mu_\beta; E[g]\mathbb{E}[g] must be known exactly, or far more precisely than μ\mu.

    8. Check yourself #

    1. You sample N(0,1)\mathcal N(0, 1) by rejection from a standard Cauchy proposal q(x)=1/(π(1+x2))q(x) = 1/(\pi(1 + x^2)). Find MM and the acceptance rate. Can you sample a Cauchy target from a Gaussian proposal?
      Answerp/q=π/2 (1+x2)e−x2/2p/q = \sqrt{\pi/2}\,(1 + x^2)e^{-x^2/2}. The derivative of (1+x2)e−x2/2(1 + x^2)e^{-x^2/2} is x(1−x2)e−x2/2x(1 - x^2)e^{-x^2/2}, so the maximum is at x=±1x = \pm 1: M=π/2⋅2e−1/2=2π e−1/2≈1.520M = \sqrt{\pi/2}\cdot 2e^{-1/2} = \sqrt{2\pi}\,e^{-1/2} \approx 1.520. Acceptance rate 1/M≈0.6581/M \approx 0.658 (normalised target, Z=1Z = 1). The reverse is impossible: Cauchy/Gaussian →∞\to \infty in the tails, so no finite MM exists.
    2. How many plain Monte Carlo draws do you need to estimate P(X>3)=1.35⋅10−3P(X > 3) = 1.35 \cdot 10^{-3} for X∼N(0,1)X \sim \mathcal N(0, 1) with 10% relative standard error?
      AnswerRelative SE ≈1/nμ=0.1\approx 1/\sqrt{n\mu} = 0.1 gives nμ=100n\mu = 100, so n≈100/(1.35⋅10−3)≈74,000n \approx 100/(1.35 \cdot 10^{-3}) \approx 74{,}000 draws (the exact formula (1−μ)/(0.01μ)(1 - \mu)/(0.01\mu) gives about 73,980).
    3. Show that SNIS is biased with a one-line example. Why is it still used?
      AnswerWith n=1n = 1, μ~=f(X1)\tilde\mu = f(X_1) with X1∼qX_1 \sim q, so E[μ~]=Eq[f]≠Ep[f]\mathbb{E}[\tilde\mu] = \mathbb{E}_q[f] \ne \mathbb{E}_p[f] in general. It is used because it needs pp only up to a constant (posteriors, energy-based models), it is consistent with an O(1/n)O(1/n) bias, and the same weights estimate ZZ.
    4. For p=N(0,1)p = \mathcal N(0, 1) and q=N(0,s2)q = \mathcal N(0, s^2), for which ss is the IS variance of the estimate of E[X2]\mathbb{E}[X^2] finite?
      AnswerThe second moment is ∫x4p2/q dx\int x^4 p^2/q\,dx with p2/q∝exp⁡(−x2(1−12s2))p^2/q \propto \exp\big(-x^2(1 - \frac{1}{2s^2})\big). This is integrable (also times x4x^4) exactly when 1−12s2>01 - \frac{1}{2s^2} > 0, that is s2>1/2s^2 > 1/2.
    5. For which of h(u)=uh(u) = u, h(u)=euh(u) = e^u, h(u)=(u−12)2h(u) = (u - \frac12)^2 do antithetic pairs help?
      Answerh(u)=uh(u) = u: h(u)+h(1−u)=1h(u) + h(1 - u) = 1, so the variance is 0. eue^u: monotone, so ρ<0\rho < 0 and it helps a lot (ρ=−0.968\rho = -0.968). (u−12)2(u - \frac12)^2: symmetric, ρ=1\rho = 1, so the variance per evaluation doubles.
    6. A control variate has correlation ρ=0.9\rho = 0.9 with ff. How many times fewer draws do you need? And if ρ=−0.9\rho = -0.9?
      AnswerThe variance factor is 1−ρ2=0.191 - \rho^2 = 0.19, so about 1/0.19≈5.31/0.19 \approx 5.3 times fewer draws. The sign does not matter: β∗\beta^* takes the sign of the covariance.
    Recall cardsAnswer in your head first, then reveal. Add the cards to your review deck to see them again just before you would forget.
    1. What is the standard error of the plain Monte Carlo estimate of E[f(X)]\mathbb{E}[f(X)] from nn i.i.d. draws?

    2. What is the relative standard error of plain Monte Carlo for an event of probability μ\mu?

    3. In rejection sampling, when do you accept a proposal x∼qx \sim q, and what is the acceptance rate?

    4. Write the importance sampling estimator of Ep[f(X)]\mathbb{E}_p[f(X)].

    5. Why must an importance sampling proposal have heavier tails than the target?

    6. What is the self-normalised IS estimator, and is it unbiased?

    7. Define the effective sample size of importance weights.

    8. What is the optimal coefficient of a control variate, and the resulting variance factor?

    9. When do antithetic variables reduce the variance, and when do they increase it?

    Open the review →

    9. Interview angle #

    • "Estimate π\pi with a random number generator. How accurate is it?" — Fraction of points in the disk times 4; standard error 4(π/4)(1−π/4)/n≈1.64/n4\sqrt{(\pi/4)(1 - \pi/4)/n} \approx 1.64/\sqrt n.
    • "You have a density up to a constant. How do you sample it?" — Inverse CDF in 1-D if you can integrate and invert; rejection with an envelope in low dimension; otherwise MCMC (lesson 15), or SNIS if you only need expectations.
    • "Why does importance sampling fail in high dimension?" — The variance of the weights grows exponentially with the dimension (ESS =n e−∥m∥2= n\,e^{-\|m\|^2} for a mean shift mm), so one weight dominates.
    • "Why is speculative decoding exact?" — Accept with min⁡(1,p/q)\min(1, p/q) and, on rejection, sample from the normalised residual max⁡(0,p−q)\max(0, p - q); the two parts add up to pp.
    • "Importance sampling or MCMC for a posterior?" — IS from a Laplace or variational approximation with heavier tails when the dimension is low and a good proposal exists: independent draws, the evidence ZZ and a weight diagnostic. MCMC when the posterior is high-dimensional or has a shape no simple proposal covers.
    • "What is a baseline in policy gradients?" — A control variate: subtracting bb keeps the estimator unbiased because E[∇log⁡π]=0\mathbb{E}[\nabla\log\pi] = 0, and reduces the variance when bb is close to the optimal value; a bad bb can increase it.

    10. Practice #

    The notebook for this lesson has five exercises, each with a check cell and a folded solution:

    1. log_sum_exp and effective_sample_size from log-weights, stable for weights like e±1000e^{\pm 1000}.
    2. importance_sampling for P(X>4)P(X > 4) with its standard error, compared with scipy.stats.norm.sf.
    3. self_normalized_is on the unnormalised mixture 3 N(−2,1)+N(3,0.52)3\,\mathcal N(-2, 1) + \mathcal N(3, 0.5^2) (so Z=4Z = 4): the mean, and Z^\hat Z.
    4. A rejection sampler for the half-normal with an Exp(1) proposal: the acceptance rate against the optimal MM.
    5. control_variate_mean and antithetic_mean, with their variance-reduction factors for ln⁡2\ln 2.

    11. Watch and read #

    Why sampling from a different distribution can reduce variance, and how the weights correct the bias.
    Open on YouTube · the player loads from youtube-nocookie.com when you press play
    The basic idea of estimating quantities by random sampling, with simple examples.
    Open on YouTube · the player loads from youtube-nocookie.com when you press play
    Monte Carlo integration, importance sampling and the move to MCMC, from a machine-learning course.
    Open on YouTube · the player loads from youtube-nocookie.com when you press play