Sampling Methods Compared: Inverse-CDF, Rejection, Importance

Hands-on guide to Monte Carlo sampling: inverse-CDF, Box-Muller, rejection, and importance sampling, with Python code, animations, and a decision matrix.

Cover Image for Sampling Methods Compared: Inverse-CDF, Rejection, Importance

You have a probability model and want an average under it, such as the expected value of a quantity in a Bayesian analysis. Drawing examples from the distribution would make that calculation easier, but knowing how to evaluate its density does not always give you a direct sampler. A custom likelihood is one situation where this can arise. We'll compare ways to turn an evaluable distribution into samples or weighted estimates. The integral

E[f]=∫f(z) p(z) dz\mathbb{E}[f] = \int f(\mathbf{z})\, p(\mathbf{z})\, \mathrm{d}\mathbf{z}

has no closed form, and the moment you discretise the space the cost grows exponentially with dimension. There is a hierarchy of fixes. Each one trades a different pair of properties: ease of implementation, sample quality, dimensionality, and how much you need to know about the target distribution.

By the end of this post, you will have implemented inverse-CDF sampling, Box-Muller, rejection sampling on a gamma target, importance sampling with a tuned proposal, and sampling-importance-resampling, all in plain NumPy. You will also see, on the same canvas, why rejection sampling collapses past a handful of dimensions and why importance sampling can give a confidently wrong answer if the proposal misses the target's mass.

Quick Win: Three Methods, Three Lines Each

Open In Colab

Pure NumPy, no scipy.stats sampler, three classic methods on simple targets:

import numpy as np
from scipy import stats

rng = np.random.default_rng(42)

# 1. Inverse-CDF: exponential samples via y = -ln(1 - z) / lambda
u = rng.uniform(0, 1, 5000)
exp_samples = -np.log1p(-u) / 1.0

# 2. Box-Muller: standard Gaussian samples from uniform pairs
z1, z2 = rng.uniform(-1, 1, 8000), rng.uniform(-1, 1, 8000)
keep = (z1**2 + z2**2 <= 1) & (z1**2 + z2**2 > 0)
z1, z2 = z1[keep], z2[keep]
r2 = z1**2 + z2**2
gauss_samples = z1 * np.sqrt(-2 * np.log(r2) / r2)

# 3. Importance sampling: estimate E[z^2] under N(0,1) using N(0, 1.5^2) proposal
sigma_q = 1.5
z = rng.normal(0, sigma_q, 5000)
log_w = stats.norm.logpdf(z, 0, 1) - stats.norm.logpdf(z, 0, sigma_q)
w = np.exp(log_w - log_w.max())
estimate = np.sum(w * z**2) / np.sum(w)  # ≈ 1.0

Each block is one method. Each runs in milliseconds on five thousand samples. They look similar on the page, but they answer different questions and break in different ways. The rest of the post pulls them apart.

What Just Happened: Inverse-CDF Sampling

The transformation method is the cleanest way to convert uniform draws into samples from a non-uniform distribution. It follows from the change-of-variables formula. If zz is uniform on (0,1)(0, 1) and y=h−1(z)y = h^{-1}(z) where hh is the cumulative distribution function (CDF) of the target, then yy follows the target distribution.

For the exponential, h(y)=1−e−λyh(y) = 1 - e^{-\lambda y}, and inverting gives

y=−1λ ln⁡(1−z)y = -\frac{1}{\lambda}\,\ln(1 - z)

Watch a uniform draw on the y-axis trace down through the CDF and land as a target-distributed sample on the x-axis. The histogram fills in beneath the target PDF as samples accumulate:

Animation showing uniform samples on the y-axis being mapped through the exponential CDF curve down to the x-axis. The bottom panel histogram fills to match the amber target PDF as samples accumulate.

import matplotlib.pyplot as plt

lam = 1.0
u = rng.uniform(0, 1, 5000)
y = -np.log1p(-u) / lam

fig, ax = plt.subplots(figsize=(7, 4))
ax.hist(y, bins=40, density=True, alpha=0.6, label="inverse-CDF samples")
y_grid = np.linspace(0, 8, 200)
ax.plot(y_grid, lam * np.exp(-lam * y_grid), lw=2, label="target PDF")
ax.set_xlabel("y"); ax.set_ylabel("density"); ax.legend()

Inverse-CDF works whenever the CDF has a closed-form inverse. That covers exponential, uniform, Cauchy, Laplace, and a handful of others. It does not cover the standard normal because its CDF (the error function) has no closed-form inverse.

For Gaussians, Box-Muller does the next-cleanest thing. It generates two independent standard Gaussians from a pair of uniform draws inside the unit circle:

y1=z1−2ln⁡r2r2,y2=z2−2ln⁡r2r2,r2=z12+z22y_1 = z_1 \sqrt{\frac{-2 \ln r^2}{r^2}}, \qquad y_2 = z_2 \sqrt{\frac{-2 \ln r^2}{r^2}}, \qquad r^2 = z_1^2 + z_2^2

The trick relies on two facts: r2r^2 is uniform on (0,1](0, 1] when (z1,z2)(z_1, z_2) is uniform inside the unit circle, and the polar transform y=z−2ln⁡r2/r2y = z\sqrt{-2 \ln r^2 / r^2} mirrors the inverse-CDF of the Rayleigh distribution. The output is a clean cloud of standard Gaussians:

Two-panel figure: left panel shows uniform draws inside the unit circle; right panel shows the resulting Box-Muller histogram of 4000 samples matching the standard normal PDF.

To draw from a multivariate Gaussian N(μ,Σ)\mathcal{N}(\boldsymbol{\mu}, \boldsymbol{\Sigma}), take the Cholesky factor Σ=LL⊤\boldsymbol{\Sigma} = \mathbf{L}\mathbf{L}^{\top} and form y=μ+Lz\mathbf{y} = \boldsymbol{\mu} + \mathbf{L}\mathbf{z} where z\mathbf{z} is a stack of independent Box-Muller draws. That covers most multivariate sampling needs in vanilla Bayesian linear regression and Gaussian processes, both treated in the Gaussian process regression post.

Going Deeper: Rejection Sampling

The transformation method runs out of road when the target's CDF is intractable. Rejection sampling takes a different approach. Suppose you can evaluate p~(z)=Zp p(z)\widetilde{p}(z) = Z_p \, p(z) up to an unknown normaliser ZpZ_p. Pick a proposal distribution q(z)q(z) you can sample from and a constant kk so that k q(z)≥p~(z)k\,q(z) \geq \widetilde{p}(z) for all zz. Then:

  1. Draw z0z_0 from qq
  2. Draw u0u_0 from Uniform(0,k q(z0))\mathrm{Uniform}(0, k\,q(z_0))
  3. If u0≤p~(z0)u_0 \leq \widetilde{p}(z_0), accept z0z_0. Otherwise, reject and try again

The accepted samples are exact draws from p(z)p(z). The acceptance probability per attempt is

p(accept)=1k∫p~(z) dzp(\text{accept}) = \frac{1}{k}\int \widetilde{p}(z)\, \mathrm{d}z

so a tighter envelope (smaller kk) means more efficient sampling. For the gamma target Gam(z∣a,b)\mathrm{Gam}(z \mid a, b) with a=2a = 2, the standard worked example uses a scaled Cauchy proposal centred at c=a−1c = a - 1 with width bq2=2a−1b_q^2 = 2a - 1. The accept-region (under p~\widetilde{p}) is solid green; the reject-region (between p~\widetilde{p} and the envelope kqkq) is grey:

Animation: Cauchy envelope above the gamma target, scattered candidate points falling under the envelope, accepted points in green and rejected in red. Bottom histogram of accepted samples grows to match the target as attempts accumulate.

from scipy.special import gamma as Gamma_fn

a, b = 2.0, 1.0
c, bq = a - 1, np.sqrt(2 * a - 1)

def gamma_pdf(z):
    return (b**a) * z**(a-1) * np.exp(-b*z) / Gamma_fn(a)

def cauchy_unnorm(z):
    return 1.0 / (1 + (z - c)**2 / bq**2)

# Pick the smallest k satisfying k * cauchy_unnorm(z) >= gamma_pdf(z) everywhere
z_grid = np.linspace(0.01, 30, 5000)
k = (gamma_pdf(z_grid) / cauchy_unnorm(z_grid)).max() * 1.001

# Draw 1000 candidates from Cauchy(c, bq), reject z<=0, then apply the test
u = rng.uniform(0, 1, 2000)
z_cand = c + bq * np.tan(np.pi * (u - 0.5))
z_cand = z_cand[z_cand > 0][:1000]
u_vert = rng.uniform(0, k * cauchy_unnorm(z_cand))
accept = u_vert <= gamma_pdf(z_cand)
samples = z_cand[accept]
print(f"accepted {accept.sum()} / {len(z_cand)} = {accept.mean():.1%}")

The end-of-run snapshot shows roughly three quarters of attempts retained:

Static snapshot: gamma target curve, Cauchy envelope, 1000 attempts coloured green (accepted, 776) or red (rejected, 224), title shows accept rate 77.6%.

For univariate problems with a well-fitting envelope, rejection sampling is fast and exact. The catch is the curse of dimensionality. Consider the case where the target is N(0,σp2I)\mathcal{N}(0, \sigma_p^2 \mathbf{I}) and the proposal is N(0,σq2I)\mathcal{N}(0, \sigma_q^2 \mathbf{I}) with σq\sigma_q even slightly larger than σp\sigma_p, the optimal kk is (σq/σp)D(\sigma_q/\sigma_p)^D, and the acceptance rate decays as (σp/σq)D(\sigma_p/\sigma_q)^D:

Acceptance rate plotted on log scale against dimension D from 1 to 100, showing exponential decay from near 1.0 at D=1 down past 0.001 at D=80, with proposal just 5% wider than target. A grey reference line marks the 0.1% acceptance threshold.

In ten dimensions, even a 5%-wider proposal already drops you to 60% acceptance. In a hundred, you are below one in twenty thousand. Rejection sampling is a one-or-two-dimensional tool. In high dimensions, you need either MCMC (covered in the Metropolis-Hastings island hopping post) or, if you only need an expectation, importance sampling.

Adaptive Rejection Sampling

A weakness of plain rejection sampling: you have to construct an envelope kqkq by hand, and a poor envelope wastes most of your attempts. Adaptive rejection sampling (Gilks and Wild, 1992) builds the envelope on the fly for the special case where ln⁡p(z)\ln p(z) is concave. Tangent lines to ln⁡p\ln p at a grid of points stay above ln⁡p\ln p everywhere; their pointwise maximum is a piecewise-linear upper bound, and exponentiating gives a piecewise-exponential envelope you can sample from cheaply:

Diagram: amber curve showing the log of a Gaussian density (a downward parabola, log-concave). Four tangent lines drawn at z = -1.8, -0.6, 0.6, 1.8 sit above the curve. A teal dashed envelope traces the maximum of the tangent lines, hugging the amber curve from above.

When a candidate is rejected, you add a tangent at its location, and the envelope tightens. The acceptance rate climbs with every rejection. The method is restricted to log-concave densities (Gaussian, exponential, gamma with a≥1a \geq 1, beta with both shape parameters at least 1). For non-log-concave targets, an adaptive-rejection-Metropolis variant (Gilks et al., 1995) lifts the restriction by composing with a Metropolis-Hastings step.

In practice, adaptive rejection is the workhorse inside Gibbs samplers (BUGS, JAGS) where the full conditional of one variable given the rest is often log-concave even when the full joint is not. We will not implement it here. The conceptual picture above is what you need to recognise it when it appears in a probabilistic programming framework.

Going Deeper: Importance Sampling

Importance sampling sidesteps the rejection problem entirely. If all you want is Ep[f(z)]\mathbb{E}_p[f(z)], not draws from pp, the trick is to draw from a different distribution and reweight:

Ep[f]=∫f(z) p(z)q(z) q(z) dz  ≃  1L∑l=1Lp(z(l))q(z(l))f(z(l))\mathbb{E}_p[f] = \int f(z) \, \frac{p(z)}{q(z)} \, q(z)\, \mathrm{d}z \;\simeq\; \frac{1}{L}\sum_{l=1}^{L} \frac{p(z^{(l)})}{q(z^{(l)})} f(z^{(l)})

Each sample contributes weight rl=p(z(l))/q(z(l))r_l = p(z^{(l)}) / q(z^{(l)}). When pp and qq are evaluable only up to normalisers, the self-normalised version keeps you honest:

Ep[f]  ≃  ∑l=1Lwlf(z(l)),wl=p~(z(l))/q~(z(l))∑mp~(z(m))/q~(z(m))\mathbb{E}_p[f] \;\simeq\; \sum_{l=1}^{L} w_l f(z^{(l)}), \qquad w_l = \frac{\widetilde{p}(z^{(l)})/\widetilde{q}(z^{(l)})}{\sum_m \widetilde{p}(z^{(m)})/\widetilde{q}(z^{(m)})}

Watch importance sampling estimate Ep[z2]=1\mathbb{E}_p[z^2] = 1 for a standard normal target using N(0,1.52)\mathcal{N}(0, 1.5^2) as the proposal. Marker size is the unnormalised weight. The running estimate (lower panel) settles near 1.0:

Animation: standard normal target curve in amber, wider Gaussian proposal q in dashed navy. Teal markers sized by importance weight pile up along q's curve. Lower panel: the running self-normalised estimate climbs and settles around 1.0 as samples accumulate.

sigma_q = 1.5
z = rng.normal(0, sigma_q, 5000)
log_w = stats.norm.logpdf(z, 0, 1) - stats.norm.logpdf(z, 0, sigma_q)
w = np.exp(log_w - log_w.max())  # subtract max for numerical stability
estimate = np.sum(w * z**2) / np.sum(w)
ess = (w.sum()**2) / (w**2).sum()
print(f"estimate = {estimate:.3f}, ESS = {ess:.0f} / {len(z)}")

Two things to call out:

Tail-heavier proposals are safer than tail-thinner ones. Importance sampling demands q(z)>0q(z) > 0 wherever p(z)f(z)p(z) f(z) is non-negligible. If qq has thinner tails than pp, weights in the regions where pp is large (and qq is small) will be huge and a few samples will dominate the sum. Box plots of the self-normalised estimator across 200 repeats with n=2000n = 2000 show this clearly:

Box plots of self-normalised importance sampling estimates for proposals sigma_q in [0.5, 1, 1.5, 2, 3]. The sigma_q=0.5 box is wide, biased low around 0.78. The remaining four are tight around 1.0.

The σq=0.5\sigma_q = 0.5 proposal has thinner tails than the target. Most weight concentrates on a few outlier samples, the estimator is biased and high-variance. The wider proposals all converge cleanly. The asymmetry is the central reason you should always overdisperse the proposal when in doubt.

Effective sample size diagnoses degeneracy. A standard diagnostic is

ESS=(∑lwl)2∑lwl2\mathrm{ESS} = \frac{(\sum_l w_l)^2}{\sum_l w_l^2}

with ESS∈[1,L]\mathrm{ESS} \in [1, L]. ESS near LL means the weights are uniform and each sample is informative. ESS near 1 means a single sample carries the entire estimate, and the apparent variance of the estimator is misleadingly small. Importance sampling with a low ESS produces results that are arbitrarily wrong with no diagnostic indication if you only look at the point estimate. That is the method's deepest failure mode.

Sampling-Importance-Resampling

What if you want actual draws from pp, not just expectations? Sampling-importance-resampling (SIR) bolts a resampling step onto the importance sampler:

  1. Draw LL samples from qq
  2. Compute normalised weights wlw_l
  3. Resample LL indices from {1,…,L}\{1, \ldots, L\} with probability wlw_l

The resampled draws approximate pp (the approximation is exact in the L→∞L \to \infty limit). Side by side: the weighted importance samples on the left collapse onto the target after resampling on the right:

Two panels. Left: target p (amber) and proposal q (dashed navy) with teal markers sized by weight, sitting on q's curve. Right: histogram of the resampled draws (unweighted) closely tracks the amber target.

sigma_q = 2.0
z = rng.normal(0, sigma_q, 500)
log_w = stats.norm.logpdf(z, 0, 1) - stats.norm.logpdf(z, 0, sigma_q)
w = np.exp(log_w - log_w.max())
w /= w.sum()
idx = rng.choice(np.arange(len(z)), size=len(z), p=w, replace=True)
z_sir = z[idx]  # approximate draws from p

SIR is the bridge from importance sampling to particle filters, sequential Monte Carlo, and any setting where you need actual samples from an intractable target. The downside is duplication: when a few weights dominate, the resample is full of repeated points, and the effective diversity is low. The same ESS diagnostic above tells you when that is happening.

Sampling Methods Compared

The five methods above answer different questions and degrade differently as the problem gets harder. The table is the point of the post:

MethodWhen it worksDimensionalityOutputFailure mode
Inverse-CDFCDF has a closed-form inverse1D usuallyExact i.i.d. samplesRequired form rarely available
Box-MullerGaussians (extends via Cholesky)Any (linear cost)Exact i.i.d. samplesGaussian-only
Rejectionp~\widetilde p evaluable, envelope kq≥p~kq \geq \widetilde p availableDies exponentially in DDExact samplesAcceptance ∼1/k\sim 1/k collapses
Adaptive rejectionLog-concave ln⁡p\ln p (or +MH variant)1DExact samplesNot log-concave breaks the envelope
Importance samplingqq covers the support of ppBetter than rejection, ESS still hurtsWeighted samplesFew weights dominate, low ESS
SIRWant unweighted draws from importance samplesSame as ISApproximate samplesDuplication, low diversity

The decision tree is shorter than the table suggests:

  1. Can you invert the CDF? Use inverse-CDF.
  2. Is the target Gaussian? Use Box-Muller plus Cholesky.
  3. Univariate, evaluable, can you build an envelope? Use rejection (or adaptive rejection if log-concave).
  4. Univariate or low-D, only need an expectation, can you find a tail-heavier proposal? Use importance sampling. Always report ESS.
  5. Need actual draws from an intractable, possibly multidimensional target? Use SIR for low-D, MCMC for the rest. The Metropolis-Hastings post picks up there.

The retention and ESS picture across the methods, on the toy problems used in this post:

Two-panel comparison: left bars show retention rate (Inverse-CDF, IS variants, SIR all at 1.0; Box-Muller 0.79; Rejection 0.75). Right bars show ESS / n (Inverse-CDF, Box-Muller, Rejection at 1.0; IS sigma_q=1.5 at 0.83; IS sigma_q=3.0 at 0.46; SIR sigma_q=2 at 0.67).

Two surprises worth pausing on. Box-Muller's "retention" is below 1.0 because the unit-circle rejection step throws out the corners of the square (π/4≈0.785\pi/4 \approx 0.785). And rejection sampling, despite producing exact samples, has the lowest retention in the toy problem (75%). That gap widens fast: on a real-world model with a posterior that is sharper than its envelope, rejection sampling can spend 99% of its effort on rejected samples even in two dimensions. The "exact" property is real but expensive.

Foundations

The basic problem this post addresses is finding the expectation of some function f(z)f(\mathbf{z}) with respect to a probability distribution p(z)p(\mathbf{z}), where the components of z\mathbf{z} might be discrete or continuous variables or some combination of the two.

The Monte Carlo approximation replaces the integral with a sample average:

f^=1L∑l=1Lf(z(l))\widehat{f} = \frac{1}{L} \sum_{l=1}^{L} f(\mathbf{z}^{(l)})

This estimator is unbiased and the variance is 1LE[(f−E[f])2]\frac{1}{L} \mathbb{E}[(f - \mathbb{E}[f])^2]. The crucial observation is that the variance does not depend on the dimensionality of z\mathbf{z}. In principle, a few independent samples suffice. The work that remains is making "independent" hold, in a setting where you cannot draw from pp directly.

The transformation method is the cleanest case: a uniform variable zz mapped via y=h−1(z)y = h^{-1}(z) where hh is the target CDF gives y∼py \sim p. Box-Muller extends this to Gaussians via a polar transform. Rejection sampling handles unnormalised targets at the cost of an exponential acceptance rate in dimension. Importance sampling, with its self-normalised form, trades the rejection rate for a weighting scheme but moves the failure mode from acceptance rate to weight degeneracy.

A point beginners often miss: importance sampling can be confidently wrong with no diagnostic indication. The estimator can be arbitrarily in error with no warning sign, which is why the sampling distribution q(z)q(\mathbf{z}) must not be small or zero in regions where p(z)p(\mathbf{z}) may be significant.

If your proposal misses a mode or has thinner tails than the target, the estimator's apparent variance is small and its bias is large. Always overdisperse and always report ESS.

The seminal references for the modern treatment are Gilks, Richardson, and Spiegelhalter's 1996 Markov Chain Monte Carlo in Practice, Robert and Casella's 1999 Monte Carlo Statistical Methods, and the Gilks and Wild 1992 paper on adaptive rejection sampling. For an article-length retrospective, Andrieu, de Freitas, Doucet, and Jordan's 2003 review is the canonical entry point and covers the bridge from these basics into MCMC.

Limitations and Pitfalls

The trade-offs are easy to summarise once you have written each method out:

  • Inverse-CDF: demands a closed-form inverse CDF. The transformation method does not generalise to multivariate targets without further structure (Cholesky for Gaussians, copulas for other dependence patterns).
  • Rejection sampling: the acceptance rate 1/k1/k collapses exponentially with dimension. A 5% mismatch between proposal and target costs you four orders of magnitude in acceptance by D=100D = 100. A practical rule: do not use rejection sampling for D≥5D \geq 5 unless the proposal is a tight envelope.
  • Adaptive rejection sampling: restricted to log-concave densities. The ARS-Metropolis variant lifts the restriction but layers a Markov-chain dependence between samples that breaks the i.i.d. property of plain rejection.
  • Importance sampling: the proposal must cover the target's support. Tail-thinner proposals produce arbitrarily wrong answers with deceptively small apparent variance. ESS is the diagnostic; treat ESS less than 10% of the sample size as a red flag.
  • SIR: approximate, not exact. Resampling introduces duplication; the effective diversity is bounded by ESS. Use SIR for getting a quick look at the posterior, not for final inference.

The natural next step from this point is MCMC, which solves the dimensionality problem at the cost of correlated samples. The Metropolis-Hastings island hopping post and the MCMC Poisson-mixture post are the worked examples on the site. The deterministic alternative, variational inference, lives in the post on approximate inference.

Interactive Tools

  • Inspect the exponential, normal and gamma density shapes used as target or proposal examples. These calculators show the PDF and CDF; they do not choose a valid rejection envelope for you.
  • Bayes' Theorem Calculator: the prior-likelihood-posterior arithmetic that posterior sampling is approximating, in a two-event toy form.
  • GP Regression Playground: a downstream use of multivariate Gaussian sampling: every posterior draw on the GP playground is a Box-Muller plus Cholesky away from the maths in this post.

Stay in the loop

Get notified when new tutorials and deep-dives are published. No spam, unsubscribe anytime.

Related Posts

Frequently Asked Questions