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
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
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 is uniform on and where is the cumulative distribution function (CDF) of the target, then follows the target distribution.
For the exponential, , and inverting gives
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:

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:
The trick relies on two facts: is uniform on when is uniform inside the unit circle, and the polar transform mirrors the inverse-CDF of the Rayleigh distribution. The output is a clean cloud of standard Gaussians:

To draw from a multivariate Gaussian , take the Cholesky factor and form where 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 up to an unknown normaliser . Pick a proposal distribution you can sample from and a constant so that for all . Then:
- Draw from
- Draw from
- If , accept . Otherwise, reject and try again
The accepted samples are exact draws from . The acceptance probability per attempt is
so a tighter envelope (smaller ) means more efficient sampling. For the gamma target with , the standard worked example uses a scaled Cauchy proposal centred at with width . The accept-region (under ) is solid green; the reject-region (between and the envelope ) is grey:

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:

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 and the proposal is with even slightly larger than , the optimal is , and the acceptance rate decays as :

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 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 is concave. Tangent lines to at a grid of points stay above everywhere; their pointwise maximum is a piecewise-linear upper bound, and exponentiating gives a piecewise-exponential envelope you can sample from cheaply:

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 , 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 , not draws from , the trick is to draw from a different distribution and reweight:
Each sample contributes weight . When and are evaluable only up to normalisers, the self-normalised version keeps you honest:
Watch importance sampling estimate for a standard normal target using as the proposal. Marker size is the unnormalised weight. The running estimate (lower panel) settles near 1.0:

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 wherever is non-negligible. If has thinner tails than , weights in the regions where is large (and is small) will be huge and a few samples will dominate the sum. Box plots of the self-normalised estimator across 200 repeats with 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.](/images/posts/sampling-methods-inverse-cdf-rejection-importance-importance-proposal-sweep.webp)
The 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
with . ESS near 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 , not just expectations? Sampling-importance-resampling (SIR) bolts a resampling step onto the importance sampler:
- Draw samples from
- Compute normalised weights
- Resample indices from with probability
The resampled draws approximate (the approximation is exact in the limit). Side by side: the weighted importance samples on the left collapse onto the target after resampling on the right:

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:
| Method | When it works | Dimensionality | Output | Failure mode |
|---|---|---|---|---|
| Inverse-CDF | CDF has a closed-form inverse | 1D usually | Exact i.i.d. samples | Required form rarely available |
| Box-Muller | Gaussians (extends via Cholesky) | Any (linear cost) | Exact i.i.d. samples | Gaussian-only |
| Rejection | evaluable, envelope available | Dies exponentially in | Exact samples | Acceptance collapses |
| Adaptive rejection | Log-concave (or +MH variant) | 1D | Exact samples | Not log-concave breaks the envelope |
| Importance sampling | covers the support of | Better than rejection, ESS still hurts | Weighted samples | Few weights dominate, low ESS |
| SIR | Want unweighted draws from importance samples | Same as IS | Approximate samples | Duplication, low diversity |
The decision tree is shorter than the table suggests:
- Can you invert the CDF? Use inverse-CDF.
- Is the target Gaussian? Use Box-Muller plus Cholesky.
- Univariate, evaluable, can you build an envelope? Use rejection (or adaptive rejection if log-concave).
- Univariate or low-D, only need an expectation, can you find a tail-heavier proposal? Use importance sampling. Always report ESS.
- 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 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 (). 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 with respect to a probability distribution , where the components of might be discrete or continuous variables or some combination of the two.
The Monte Carlo approximation replaces the integral with a sample average:
This estimator is unbiased and the variance is . The crucial observation is that the variance does not depend on the dimensionality of . In principle, a few independent samples suffice. The work that remains is making "independent" hold, in a setting where you cannot draw from directly.
The transformation method is the cleanest case: a uniform variable mapped via where is the target CDF gives . 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 must not be small or zero in regions where 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 collapses exponentially with dimension. A 5% mismatch between proposal and target costs you four orders of magnitude in acceptance by . A practical rule: do not use rejection sampling for 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.
Related Posts
- Approximate Inference: From MCMC to Variational Bayes: the deterministic counterpart to the stochastic methods here. Variational inference is the alternative when sampling is too slow.
- MCMC Metropolis-Hastings: Island Hopping Guide: the direct sequel for high-dimensional targets where rejection collapses.
- MCMC for Mixture Models: Inferring Earthquake Regimes: a real-world MCMC application on a Poisson-mixture posterior the methods in this post cannot reach.
- From MLE to Bayesian Inference: the foundation post on why we want posterior expectations in the first place.
- Gaussian Process Regression from Scratch: multivariate Gaussian sampling via Cholesky, the workhorse downstream of Box-Muller.





