Sampling from probability distributions
| Problem | Turn uniform random numbers into samples from a given distribution: continuous (normal, gamma, beta, …), discrete (Poisson, binomial, …) or multivariate (multivariate normal, Dirichlet) |
| Devised by | Inversion: John von Neumann and Stanisław Ulam (1940s); rejection: von Neumann (1951); George Box and Mervin Muller (1958), normal pairs; Joachim Ahrens and Ulrich Dieter (1974), gamma, Poisson and binomial recursions; George Marsaglia and Wai Wan Tsang (2000), gamma |
| Accuracy | Exact in distribution (up to the 53-bit resolution of the uniforms); every sampler passes a Kolmogorov-Smirnov test at 100 000 samples (table below) |
| Cost | 1–60 ns per sample: one or two uniforms for inversion and Box-Muller, a few for rejection |
| Read first | Pseudo-random number generators, Statistical distribution functions |
| API | distributions: uniform_distribution, exponential_distribution, weibull_distribution, gaussian_distribution_box_muller, log_normal_distribution, chi_square_distribution, students_t_distribution, gamma_distribution, beta_distribution, cauchy_distribution, bernoulli_distribution, geometric_distribution, poisson_distribution_knuth, binomial_distribution, dirichlet_distribution, MultivariateNormal |
Overview
A handful of general techniques turn uniform samples into samples from any distribution. Inversion applies the inverse CDF: if is uniform, has distribution . It is exact and uses one uniform per sample, but needs a cheap inverse CDF. Transformations exploit special structure, such as the polar form of two independent normals. Rejection samples from a simpler envelope distribution and accepts each proposal with a probability that corrects the shape. Composition builds a distribution from others: a beta from two gammas, Student’s from a normal and a chi-square, a Dirichlet vector from normalised gammas, a multivariate normal from a linear map of independent normals.
Where it is used
Simulations need random numbers with a particular distribution.
- Monte Carlo analysis. Tolerance analysis of circuits, reliability of structures, and risk analysis in finance draw inputs from normal, lognormal, exponential and other distributions.
- Communications. Simulating a noisy channel needs Gaussian noise; fading channels need Rayleigh and Rician variates.
- Machine learning and statistics. Weight initialisation, bootstrap resampling and synthetic data.
History
Inversion and rejection were developed by John von Neumann and Stanisław Ulam for the first Monte Carlo computations on ENIAC in the late 1940s; von Neumann’s 1951 paper “Various techniques used in connection with random digits” introduced rejection sampling. George Box and Mervin Muller (1958) found the transformation that gives exact normal pairs from two uniforms. Joachim Ahrens and Ulrich Dieter (1970s) designed fast exact samplers for the gamma, Poisson and binomial distributions, collected with many others in Luc Devroye’s Non-Uniform Random Variate Generation (1986). George Marsaglia and Wai Wan Tsang’s gamma sampler (2000), a rejection from a transformed normal that accepts over 95% of proposals, is the modern default.
The idea
Inversion
A generator supplies uniform numbers on . Every other distribution must be manufactured from them, and there are three general techniques: inversion, transformation and rejection.
Inversion uses the cumulative distribution function . If is continuous and increasing, set
To see that has the right distribution, compute its CDF. Since is increasing, exactly when , and for a uniform variable the probability of being below a number in is itself:
Example: the exponential distribution. With rate its CDF is . Solving for gives
Since is also uniform, one could write instead. The library keeps , because can be exactly 0, and is infinite, whereas is never 0.
The Weibull, the Cauchy () and, after rounding down, the geometric distribution are sampled in the same way. Inversion needs a formula for , which many distributions (the normal among them) do not have. For discrete distributions, inversion becomes a search: find the smallest with .
The normal distribution: Box-Muller
The normal CDF cannot be inverted in closed form, but a pair of normals can be produced by a change of variables. If and are independent uniforms, then
are independent standard normals.
The reason is easiest to see backwards. Take two independent standard normals and regard them as the coordinates of a point in the plane. Their joint density is proportional to , which depends only on the distance from the origin. So the direction of the point is uniform over the circle, and independent of its distance. As for the distance, integrate the density over the disc of radius in polar coordinates, where the area element is : the probability that the point lies within distance is , so : has an exponential distribution with mean 2. Both ingredients are easy to sample: the angle is , and by inversion the squared radius is . Converting the polar coordinates back to Cartesian ones gives the formulas above.
The library returns both values, and scales them to as . Several other distributions are built on the normal by their definitions: the log-normal is ; the chi-square with degrees of freedom is the sum of squared normals; Student’s is a normal divided by .
Rejection: the gamma distribution
When neither inversion nor a transformation is available, rejection sampling almost always is. Picture the region under the graph of the density . If points are scattered uniformly over that region, their -coordinates have density , because the chance of landing in a thin vertical strip is proportional to its height. The difficulty is scattering points uniformly under . Rejection does it indirectly:
- Choose an envelope: a density that is easy to sample, and a constant such that everywhere, so that the graph of lies above that of .
- Draw from and an independent uniform . The point is uniform under the graph of .
- Accept if the point lies under the graph of , that is if . Otherwise reject it and return to step 2.
The accepted points are uniform under , so the accepted values have density . The area under is and the area under is 1, so the probability of acceptance is and on average proposals are needed per sample. A good envelope hugs the density closely.
Marsaglia and Tsang’s gamma sampler is a refined example, for shape . It sets with normal, and . The cube of a normal variable, suitably shifted and scaled, already has a distribution very close to the gamma, so the rejection step only has to correct a small discrepancy: the value is accepted when with , which happens more than 95% of the time.
Shapes below 1 use the identity . Other distributions follow from gammas: the beta distribution is for independent gammas of shapes and , and the Dirichlet normalises a vector of gammas to sum to 1.
Discrete distributions: Poisson and binomial
A Poisson variable with rate counts the events of a Poisson process, in which events occur independently at an average rate , during one unit of time. The gaps between successive events of such a process are independent exponentials with rate . So one way to sample is to add up exponential gaps until their sum exceeds 1, and count how many fitted.
Knuth’s sampler is this idea with the logarithms removed. Each gap is , so the sum of the gaps exceeds 1 exactly when the product of the uniforms falls below . The sampler multiplies uniforms together until that happens, and returns the number of factors, less one. It needs about uniforms, so it is suitable only for small rates.
For large the library uses the exact recursion of Ahrens and Dieter, which avoids simulating every event. Let , and draw the time of the -th event directly, as a variable (the sum of exponential gaps).
- If is before the end of the interval, at least events have occurred, and the count is plus a Poisson count for the remaining time, with the smaller rate .
- If is after the end, fewer than events occurred. The earlier events are uniformly distributed over , so the number of them that fall inside the interval is binomial.
Either way the problem has been reduced to a much smaller one. The binomial sampler uses inversion for small means, and otherwise splits recursively in a similar way, on a beta-distributed order statistic, in beta samples.
The original Poisson sampler multiplied one uniform by itself, with its loop condition inverted, and returned for every .
Multivariate normal
If is the Cholesky factorisation of a covariance matrix and is a vector of independent
standard normals, then is . MultivariateNormal factorises once and samples in .
Testing the samplers
For each distribution, 100 000 samples are compared with the exact moments and CDF (from the special functions). The Kolmogorov-Smirnov statistic , the largest difference between the empirical and the exact CDF, should be below about 95% of the time:
Table 9.4. Sample moments of each sampler against the exact values.
| distribution | method | sample mean (exact) | sample variance (exact) | KS statistic |
|---|---|---|---|---|
| uniform | scaling | 1.0031 (1.0000) | 1.3314 (1.3333) | 0.0024 |
| exponential, rate 2 | inversion | 0.5006 (0.5000) | 0.2540 (0.2500) | 0.0019 |
| Weibull, shape 1.5, scale 2 | inversion | 1.8151 (1.8055) | 1.5205 (1.5028) | 0.0043 |
| normal | Box-Muller | 1.0069 (1.0000) | 3.9767 (4.0000) | 0.0038 |
| log-normal, , | exp of a normal | 1.1342 (1.1331) | 0.3656 (0.3647) | 0.0018 |
| chi-square, | sum of squared normals | 4.9938 (5.0000) | 9.9272 (10.0000) | 0.0017 |
| Student’s , | normal over | 0.0028 (0.0000) | 1.6549 (1.6667) | 0.0023 |
| gamma, shape 2.5, scale 2 | Marsaglia-Tsang | 5.0023 (5.0000) | 10.0014 (10.0000) | 0.0024 |
| gamma, shape 0.3 | Marsaglia-Tsang with boosting | 0.2986 (0.3000) | 0.2995 (0.3000) | 0.0020 |
| beta | ratio of gammas | 0.2857 (0.2857) | 0.0257 (0.0255) | 0.0023 |
| Cauchy | inversion | (none) | (none) | 0.0032 |
| Bernoulli, | comparison | 0.2979 (0.3000) | 0.2092 (0.2100) | 0.0021 |
| geometric, (failures) | inversion | 4.0329 (4.0000) | 20.3440 (20.0000) | 0.0034 |
| Poisson, | Knuth’s products | 4.0028 (4.0000) | 4.0114 (4.0000) | 0.0013 |
| Poisson, | Ahrens-Dieter recursion | 299.9857 (300.0000) | 300.5645 (300.0000) | 0.0014 |
| binomial, , | inversion | 5.9981 (6.0000) | 4.1773 (4.2000) | 0.0014 |
| binomial, , | beta splitting | 40000.1401 (40000.0000) | 24016.5330 (24000.0000) | 0.0031 |
With samples the 5% critical value of is .
All pass; the Weibull’s sits at the critical value, which is to be expected for one of seventeen tests at the 5% level (with other seeds its mean is within standard errors). The histograms show three of the samples against their densities:
Figure 9.1. Histograms against densities.
Algorithm
Each sampler is a few lines; these are the main ones.
Exponential with rate (inversion): draw ; return .
Normal (Box-Muller): draw and ; compute (taking care that the argument of the logarithm is never zero) and ; return the pair , . For return .
Gamma with shape (Marsaglia and Tsang). Set and . Repeat:
- draw a standard normal and set ; if , start again;
- draw a uniform ; if , return .
For , sample with shape and multiply by . Multiply by the scale parameter at the end.
Beta: draw and ; return .
Poisson with a small rate (Knuth): set , and ; repeat “multiply by a new uniform and add 1 to ” until ; return . For a large rate, use the recursion on the time of the -th event described above, which ends in a call with a small rate.
Multivariate normal : factor once; for each sample draw a vector of independent standard normals and return .
A discrete distribution by inversion: draw ; add up the probabilities until the running total reaches ; return the index reached.
Implementation
Box-Muller:
/// Gaussian distribution (via Box - Muller transform)
/// Yields two independent samples
pub fn gaussian_distribution_box_muller<U>(
uniform_generator: &mut U,
mean: f64,
sd: f64,
) -> (f64, f64)
where
U: UniformGenerator,
{
let uniform_sample_0: f64 = uniform_generator.next_f64();
let uniform_sample_1: f64 = uniform_generator.next_f64();
// 1 − u lies in (0, 1], so the logarithm is finite (u itself can be exactly 0).
let a = (1.0 - uniform_sample_0).ln().mul(-2.0).sqrt();
let z1 = a * uniform_sample_1.mul(2.0 * PI).cos();
let z2 = a * uniform_sample_1.mul(2.0 * PI).sin();
(z1 * sd + mean, z2 * sd + mean)
}
Marsaglia-Tsang:
/// A gamma sample with shape `alpha` and **scale** `beta` (mean `αβ`, variance `αβ²`), by the
/// Marsaglia-Tsang method (2000): a squeeze-accelerated rejection from a transformed normal, for
/// `α ≥ 1`; for `α < 1`, `Gamma(α) = Gamma(α + 1) · U^{1/α}`.
pub fn gamma_distribution<U>(uniform_generator: &mut U, alpha: f64, beta: f64) -> Result<f64,ErrorsJSL> where U : UniformGenerator{
if alpha <= 0.0 || beta <= 0.0 {
return Err(ErrorsJSL::InvalidInputRange("alpha and beta must be positive"));
}
if alpha < 1.0 {
// Boosting identity for alpha < 1
let u = uniform_generator.next_f64();
return Ok(gamma_distribution(uniform_generator,alpha + 1.0, 1.0).expect("Already sanitized") * u.powf(1.0 / alpha) * beta);
}
let d = alpha - 1.0 / 3.0;
let c = 1.0 / (9.0 * d).sqrt();
loop {
let z = gaussian_distribution_box_muller(uniform_generator, 0.0, 1.0).0;
let v = 1.0 + c * z;
if v <= 0.0 {
continue; // Reject
}
let v_cubed = v * v * v;
let u = uniform_generator.next_f64();
if u.ln() < 0.5 * z * z + d - d * v_cubed + d * v_cubed.ln() {
return Ok(d * v_cubed * beta);
}
}
}
Poisson:
/// A Poisson(`lambda`) sample (returned as `f64`), for `lambda ≥ 0`.
///
/// Small `λ` (below 16) uses Knuth's multiplication method, a fresh uniform per step. Larger `λ`
/// use the exact recursion of Ahrens and Dieter (Knuth, *TAOCP* 3.4.1): with `m = ⌊7λ/8⌋` and
/// `G ~ Gamma(m, 1)` (the time of the `m`-th event of a unit-rate Poisson process), the count is
/// `m + Poisson(λ − G)` if `G < λ`, and `Binomial(m − 1, λ/G)` otherwise, so the cost grows only
/// logarithmically in `λ`. (An earlier version reused one uniform throughout, with its loop
/// condition inverted, and returned −1 for every `λ`.) Returns `NaN` for negative or NaN `λ`.
pub fn poisson_distribution_knuth<U>(uniform_generator: &mut U, lambda: f64) -> f64
where
U: UniformGenerator,
{
if lambda.is_nan() || lambda < 0.0 || lambda.is_infinite() {
return f64::NAN;
}
let (mut lambda, mut offset) = (lambda, 0u64);
while lambda >= 16.0 {
let m = (0.875 * lambda).floor() as u64;
let g = gamma_distribution(uniform_generator, m as f64, 1.0).expect("m ≥ 14 is a valid shape");
if g < lambda {
offset += m;
lambda -= g;
} else {
let b = binomial_distribution(uniform_generator, m - 1, lambda / g).expect("λ/G lies in [0, 1]");
return (offset + b) as f64;
}
}
(offset + poisson_small(uniform_generator, lambda)) as f64
}
- Parameter conventions: the exponential and Poisson take a rate, the gamma a shape and a scale, the geometric counts failures before the first success.
- The chi-square and Student’s samplers draw normals with a given mean and standard deviation; use mean 0 and 1 for the standard distributions.
- Invalid parameters give errors (or
NaNfor the Poisson sampler, which returns a baref64).
In practice
//! Sampling from probability distributions.
//!
//! Run with `cargo run -p lib_jsl_random --example random_distributions`.
use lib_jsl_random::distributions::{
MultivariateNormal, beta_distribution, binomial_distribution, dirichlet_distribution, exponential_distribution, gamma_distribution,
gaussian_distribution_box_muller, poisson_distribution_knuth,
};
use lib_jsl_random::uniform_generator::UniformRNG;
fn main() {
let mut rng = UniformRNG::from_seed(2025);
// Waiting times of a Poisson process with rate 3 per hour, and counts per hour.
let waits: Vec<f64> = (0..5).map(|_| exponential_distribution(&mut rng, 3.0)).collect();
println!("waiting times (hours): {waits:.3?}");
let counts: Vec<f64> = (0..8).map(|_| poisson_distribution_knuth(&mut rng, 3.0)).collect();
println!("events in 8 hours: {counts:?}");
// Normal samples come in pairs from Box-Muller.
let (z1, z2) = gaussian_distribution_box_muller(&mut rng, 0.0, 1.0);
println!("two normals: {z1:.4}, {z2:.4}");
// Gamma (shape, scale), beta from two gammas, binomial for 10⁶ trials.
println!("gamma(2, 1.5): {:.4}", gamma_distribution(&mut rng, 2.0, 1.5).unwrap());
println!("beta(2, 5): {:.4}", beta_distribution(&mut rng, 2.0, 5.0).unwrap());
println!("binomial(10⁶, 0.3): {}", binomial_distribution(&mut rng, 1_000_000, 0.3).unwrap());
// A Dirichlet sample is a random probability vector.
let p = dirichlet_distribution(&mut rng, &[1.0, 2.0, 3.0]).unwrap();
println!("Dirichlet(1, 2, 3): {p:.4?}, sum {:.6}", p.iter().sum::<f64>());
// Correlated normal pairs with correlation 0.8.
let mvn = MultivariateNormal::new(vec![0.0, 0.0], &[vec![1.0, 0.8], vec![0.8, 1.0]]).unwrap();
let pairs: Vec<Vec<f64>> = (0..20_000).map(|_| mvn.sample(&mut rng)).collect();
let corr = pairs.iter().map(|p| p[0] * p[1]).sum::<f64>() / pairs.len() as f64;
println!("sample correlation of 20 000 pairs: {corr:.3}");
}
Strengths
- Exact samplers for the common distributions, tested against their CDFs.
- Generic over the uniform generator.
Weaknesses
- Box-Muller needs a logarithm, a square root and a sine and cosine per pair; the ziggurat method is several times faster.
- No sampler for arbitrary user densities (see MCMC for unnormalised densities).
Exercises
- Derive the inversion formula for the Weibull distribution from its CDF .
- Prove that the Box-Muller transformation gives independent standard normals, using the Jacobian of the polar change of variables.
- Sample the half-normal distribution by rejection from an exponential envelope, and find the best rate and the acceptance rate.
- Show that if and are independent then .
- Check the
MultivariateNormalsampler by estimating the covariance of samples of a case.
Hints and answers
- Solve for : , and since is also uniform, works.
- For independent uniforms, and have joint density on , . The map has Jacobian , so has density , a product of two standard normal densities.
- The target is and the envelope . The ratio is largest at , where it equals ; this is smallest for , giving and an acceptance rate .
- The joint density is . Put and (Jacobian ): it factorises as , so , independent of .
- The sample covariance should match the target matrix to within about relative to the entries’ scale.
Further reading
- L. Devroye, Non-Uniform Random Variate Generation, Springer, 1986 (free online from the author).
- G. Marsaglia and W. W. Tsang, “A simple method for generating gamma variables”, ACM Transactions on Mathematical Software 26 (2000) 363–372.
- G. E. P. Box and M. E. Muller, “A note on the generation of random normal deviates”, Annals of Mathematical Statistics 29 (1958) 610–611.
- J. H. Ahrens and U. Dieter, “Computer methods for sampling from gamma, beta, Poisson and binomial distributions”, Computing 12 (1974) 223–246.