Random variate generation from a given density: alias, rejection, inversion
| Problem | Generate random numbers from a distribution given only by its density (or probability mass function, or distribution function), quickly and with a known error, without a hand-made generator for each distribution |
| Devised by | Alastair Walker (1974, 1977), the alias method, in Michael Vose’s form (1991); Gilks and Wild (1992), adaptive rejection sampling; Wolfgang Hörmann (1995), transformed density rejection; Albert Kinderman and John Monahan (1977), the ratio of uniforms; Wolfgang Hörmann and Josef Leydold (2003), numerical inversion by Hermite interpolation; Gerhard Derflinger, Hörmann and Leydold (2010), polynomial inversion from the density alone; Leydold (2001), the simple ratio of uniforms; the UNU.RAN library of Leydold and Hörmann, which scipy.stats.sampling wraps |
| Accuracy | Rejection and alias sampling are exact (up to the uniform generator). Inversion is exact to a chosen u-resolution, by default |
| Cost | Alias: set-up , then one uniform per variate. Rejection: a few evaluations of the density per variate. Inversion: set-up of a few thousand density and distribution evaluations, then a search and a cubic per variate |
| Read first | Sampling from probability distributions |
| API | DiscreteAliasUrn, DiscreteGuideTable, TransformedDensityRejection, NumericalInverseHermite, rvs_ratio_uniforms, SimpleRatioUniforms, NumericalInversePolynomial, FastGeneratorInversion |
Overview
The distributions that have their own generator, normal, gamma, binomial and so on, are few. In practice one often has a density, perhaps unnormalised, from a model or a fit, and needs samples from it. The methods of this entry do that for any density that has a certain shape, or for any distribution function:
- the alias method and guide-table inversion sample a discrete distribution given by its probabilities;
- transformed density rejection samples any log-concave density, using its tangents to build a bounding curve;
- the ratio of uniforms needs only the density and a rectangle that contains a certain region;
- numerical inversion by Hermite interpolation samples any distribution whose distribution function and density can be evaluated, by tabulating the quantile function.
Each generator draws from any UniformGenerator, and the densities are closures. The results are exact or accurate to a stated resolution, but they are not SciPy’s numbers for the same seed, since the uniform streams differ.
Where it is used
Sometimes only the density of a distribution is known.
- Custom distributions. Sampling from a fitted or measured density in simulation of materials, noise and particle physics.
- Fast sampling from discrete distributions. The alias method draws from a table of probabilities in constant time, used in language models and simulation.
- Rejection and inversion. The two basic ideas that all of the more elaborate generators build on.
History
Walker published the alias method in 1974 and 1977 as a way to sample a discrete distribution in constant time, and Michael Vose (1991) gave the simple linear-time construction used here. The guide table is older: Chen and Asau (1974) added it to sequential inversion to shorten the search. Rejection from a hat made of tangents is due to Gilks and Wild (1992), who made it adaptive: each rejected point refines the hat. Hörmann (1995) generalised the construction from the logarithm to other transformations and called it transformed density rejection. Kinderman and Monahan (1977) found that a uniform point in a certain planar region, divided coordinate by coordinate, has the wanted density. Hörmann and Leydold (2003) made numerical inversion practical with the Hermite interpolation of the quantile function that this entry describes. The UNU.RAN library collected these methods behind one interface, and SciPy 1.8 wrapped them in scipy.stats.sampling.
The idea
The alias method
Take equally likely columns. Give each column one outcome with probability and an alias, another outcome, for the rest. A variate is then: pick a column uniformly, then keep its own outcome with probability and otherwise return the alias. The columns are built by pairing: an outcome with probability below is given a column of its own, and the column is topped up with an outcome of probability above , whose remaining probability then falls by the amount used. Repeating this fills all columns in steps. One uniform number does both choices: its integer part picks the column and its fractional part is compared with .
Guide-table inversion
Sequential inversion returns the first with , which takes comparisons. A guide table stores, for each of equal slices of , the first whose cumulative probability reaches the slice’s lower end. The search for a given starts there, and with slices it takes a constant number of steps on average.
Transformed density rejection
If is concave, its tangent lines lie above it. At construction points with slopes the minimum of the tangents is a concave piecewise-linear bound, so The hat is made of exponential pieces, each easy to integrate and to invert. To sample: choose a piece with probability proportional to its area, invert the exponential distribution function within it to get , and accept if with uniform on . The accepted points have density proportional to exactly. When is rejected it becomes a new construction point, which cuts the hat down where it was loosest; this keeps the sampler exact while its acceptance rate rises (Gilks and Wild’s adaptive rejection sampling).
The tails need care: for an infinite interval the outermost tangents must slope towards zero, positive at the left end and negative at the right, or the hat has infinite area. The construction starts at a point near the mode and steps outward until the slopes have the right signs, and then adds points further out, where a density that is not log-concave usually gives itself away: the slopes of at the construction points must not increase from left to right.
The ratio of uniforms
If is uniform on then has density proportional to . The region is bounded when and are bounded, and contained in . Points are drawn from that rectangle and kept if they fall in the region. A shift of the centre, , can enlarge the region’s acceptance rate.
Numerical inversion by Hermite interpolation
The quantile function has derivative . At the ends of an interval in , , the values , , , and the derivatives , determine a cubic in that interpolates on (the cubic Hermite polynomial). The interval is accepted when the cubic inverts well in the middle: with , and otherwise halved in . For smooth densities the interpolation error falls like the fourth power of the interval, so a few thousand intervals reach . A quantile or a variate then costs a binary search of the table of and one cubic. Infinite tails are cut where or falls below . The u-error measures the result.
Algorithm
Alias set-up for probabilities (normalised to sum to 1) and scaled values :
- Put the indices with in a list
smalland the others inlarge. - While both lists are non-empty: take from
smalland fromlarge. Set the column of : probability , alias . Set , and move tosmallif it is now below 1. - The columns left over get probability 1.
Transformed density rejection, one variate:
- Draw uniform in and find the piece that holds it by binary search of the cumulative areas.
- Invert the exponential distribution function of the piece at the remaining area to get .
- If for a fresh uniform , return .
- Otherwise add to the construction points (if there are fewer than 100 and stays concave there), rebuild the hat, and go to 1.
Hermite inversion, set-up: divide into 20 equal parts, and check each part as above, halving in the parts that fail, until none does.
The simple ratio of uniforms
Ratio of uniforms needs a bounding rectangle, which for a unimodal density with its mode at is with and (Leydold’s SROU). The library finds the two suprema numerically, by a scan over geometrically spaced points and a golden-section search, so the density needs neither normalising nor a derivative.
Reproducing NumPy’s streams
lib_jsl_random::numpy::Pcg64::from_seed(seed) is NumPy’s default_rng(seed): the SeedSequence mixing of the seed into four 64-bit words, then the PCG64 generator (a 128-bit linear congruential generator with the XSL-RR output function), with next_f64 equal to Generator.random(). It is checked against NumPy’s random() and random_raw() for seeds of one to three words. Any function here that takes a generator then draws the numbers SciPy draws for random_state=seed, so the library’s output can be compared with SciPy’s value for value where the algorithms agree.
The multivariate ratio of uniforms
In dimensions the region is for a unimodal density with mode , and has density proportional to when is uniform on it. It lies in the box , . MultivariateRatioUniforms::new(pdf, mode) finds those suprema by a derivative-free search (coordinate and random directions with an adaptive step, from several starting points, with a 1 % margin) or takes the box from you (with_bounds). The acceptance rate falls with the dimension: 27 % for the normal density at and about 7 % at .
Numerical inversion by polynomial interpolation
When only the density is known, the distribution function is built from it: the integral of the density over each interval, by adaptive Gauss-Legendre quadrature. On an interval of mass , take the Chebyshev-Lobatto points , find the probabilities at them, and interpolate as a polynomial in through (Newton’s form, degree 5 by default). The interval is accepted when the polynomial inverts the integral to within of the whole mass at three interior points, and otherwise halved. The result is the same table as before, built from the density alone (Derflinger, Hörmann and Leydold’s PINV). FastGeneratorInversion is this method with a location and a scale.
Implementation
/// Walker's alias method (SciPy's `DiscreteAliasUrn`, Vose's construction): after `O(n)` set-up,
/// each variate costs one uniform and one comparison. Each of `n` equally likely columns holds its
/// own outcome with some probability and an *alias* otherwise.
#[derive(Clone, Debug)]
pub struct DiscreteAliasUrn {
probability: Vec<f64>,
alias: Vec<usize>,
}
impl DiscreteAliasUrn {
/// From (unnormalised) probabilities `pmf[k]` of the outcomes `0..n`.
pub fn new(pmf: &[f64]) -> Result<Self, ErrorsJSL> {
let total = check_pmf(pmf)?;
let n = pmf.len();
let mut scaled: Vec<f64> = pmf.iter().map(|p| p * n as f64 / total).collect();
let (mut small, mut large): (Vec<usize>, Vec<usize>) = (Vec::new(), Vec::new());
for (i, &s) in scaled.iter().enumerate() {
if s < 1.0 { small.push(i) } else { large.push(i) }
}
let (mut probability, mut alias) = (vec![1.0; n], (0..n).collect::<Vec<_>>());
while let (Some(&s), Some(&l)) = (small.last(), large.last()) {
small.pop();
probability[s] = scaled[s];
alias[s] = l;
scaled[l] -= 1.0 - scaled[s];
if scaled[l] < 1.0 {
large.pop();
small.push(l);
}
}
// What is left (by rounding) has probability one.
Ok(DiscreteAliasUrn { probability, alias })
}
/// One variate.
pub fn rvs_one<G: UniformGenerator>(&self, rng: &mut G) -> usize {
let x = rng.next_f64() * self.probability.len() as f64;
let k = (x as usize).min(self.probability.len() - 1);
if x - (k as f64) < self.probability[k] { k } else { self.alias[k] }
}
/// `n` variates.
pub fn rvs<G: UniformGenerator>(&self, n: usize, rng: &mut G) -> Vec<usize> {
(0..n).map(|_| self.rvs_one(rng)).collect()
}
}
/// Transformed density rejection with the logarithm as the transformation (SciPy's
/// `TransformedDensityRejection`; Gilks and Wild's adaptive rejection sampling, Hörmann's
/// formulation) for a log-concave density `f` on `(a, b)`.
///
/// The tangents of `log f` at a set of construction points bound `log f` above by a concave
/// piecewise-linear function; its exponential is a *hat* made of exponential pieces, which can be
/// sampled by inversion. A point `x` from the hat is accepted if `u · hat(x) ≤ f(x)`. Every
/// rejected point is added as a new construction point, so the hat tightens where it matters; the
/// variates stay exact whatever the number of points.
pub struct TransformedDensityRejection<'a> {
pdf: Box<dyn Fn(f64) -> f64 + 'a>,
dpdf: Box<dyn Fn(f64) -> f64 + 'a>,
domain: (f64, f64),
/// Construction points, their `log f`, and the slopes of `log f` there.
x: Vec<f64>,
logf: Vec<f64>,
slope: Vec<f64>,
/// The hat's pieces: `[lo, hi, point index, integral]`, left to right.
pieces: Vec<(f64, f64, usize, f64)>,
/// The areas of the pieces up to and including each, for the search.
cumulative: Vec<f64>,
total: f64,
max_points: usize,
}
impl<'a> TransformedDensityRejection<'a> {
/// `pdf` and its derivative `dpdf` on the interval `domain` (ends may be infinite);
/// `center` is a point near the mode where the construction starts (SciPy's `mode` or
/// `center`). The density need not be normalised.
pub fn new(pdf: impl Fn(f64) -> f64 + 'a, dpdf: impl Fn(f64) -> f64 + 'a, domain: (f64, f64), center: f64) -> Result<Self, ErrorsJSL> {
if !matches!(domain.0.partial_cmp(&domain.1), Some(std::cmp::Ordering::Less)) || !(domain.0..=domain.1).contains(¢er) {
return Err(bad("the domain must be a non-empty interval containing the centre"));
}
let mut t = TransformedDensityRejection { pdf: Box::new(pdf), dpdf: Box::new(dpdf), domain, x: Vec::new(), logf: Vec::new(), slope: Vec::new(), pieces: Vec::new(), cumulative: Vec::new(), total: 0.0, max_points: 100 };
// The starting points: the centre, then outward until the slope of log f has the sign
// that makes the tails of the hat integrable (positive on the left, negative on the right).
let centre = if t.finite_positive(center) { center } else { return Err(bad("the density must be positive at the centre")) };
t.insert(centre)?;
let spread = if domain.0.is_finite() && domain.1.is_finite() { (domain.1 - domain.0) / 8.0 } else { 1.0 };
let mut step = spread;
if !domain.0.is_finite() || t.slope[0] <= 0.0 {
let mut x = centre;
for _ in 0..200 {
x = (x - step).max(domain.0);
if t.finite_positive(x) {
t.insert(x)?;
if t.slope[t.x.iter().position(|&v| v == x).expect("inserted")] > 0.0 || x <= domain.0 {
break;
}
} else {
step *= 0.5;
x += step * 2.0;
}
step *= 2.0;
}
}
step = spread;
if !domain.1.is_finite() || *t.slope.last().expect("a point") >= 0.0 {
let mut x = centre;
for _ in 0..200 {
x = (x + step).min(domain.1);
if t.finite_positive(x) {
t.insert(x)?;
if t.slope[t.x.iter().position(|&v| v == x).expect("inserted")] < 0.0 || x >= domain.1 {
break;
}
} else {
step *= 0.5;
x -= step * 2.0;
}
step *= 2.0;
}
}
// A few points beyond the first ones in each tail, where a density that is not
// log-concave usually shows it, then a few more between for a reasonable first hat.
let (first, last) = (t.x[0], *t.x.last().expect("points"));
for k in 1..=3 {
let reach = spread * 2f64.powi(k);
for x in [first - reach, last + reach] {
if x > domain.0 && x < domain.1 && t.finite_positive(x) {
t.insert(x)?;
}
}
}
let (lo, hi) = (t.x[0], *t.x.last().expect("points"));
for k in 1..8 {
let x = lo + (hi - lo) * k as f64 / 8.0;
if t.finite_positive(x) && !t.x.contains(&x) {
t.insert(x)?;
}
}
// Log-concavity, as far as the construction points can tell: the slopes of log f must not
// increase from left to right.
if t.slope.windows(2).any(|w| w[1] > w[0] + 1e-9 * (1.0 + w[0].abs())) {
return Err(bad("the density is not log-concave (the slope of log f increases between construction points)"));
}
t.rebuild()?;
Ok(t)
}
fn finite_positive(&self, x: f64) -> bool {
let f = (self.pdf)(x);
f.is_finite() && f > 0.0
}
/// Adds a construction point, keeping the points sorted.
fn insert(&mut self, x: f64) -> Result<(), ErrorsJSL> {
let f = (self.pdf)(x);
if !(f.is_finite() && f > 0.0) {
return Err(bad("the density must be positive and finite at the construction points"));
}
let s = (self.dpdf)(x) / f;
if !s.is_finite() {
return Err(bad("the derivative of the density must be finite"));
}
let k = self.x.partition_point(|&v| v < x);
if self.x.get(k) == Some(&x) {
return Ok(());
}
let tol = |v: f64| 1e-9 * (1.0 + v.abs());
if (k > 0 && s > self.slope[k - 1] + tol(s)) || (k < self.x.len() && s < self.slope[k] - tol(s)) {
return Err(bad("the density is not log-concave"));
}
self.x.insert(k, x);
self.logf.insert(k, f.ln());
self.slope.insert(k, s);
Ok(())
}
/// The hat's pieces and total area from the construction points.
fn rebuild(&mut self) -> Result<(), ErrorsJSL> {
let n = self.x.len();
let mut pieces = Vec::with_capacity(n + 1);
let mut total = 0.0;
let area = |a: f64, lo: f64, hi: f64, s: f64, x0: f64, logf0: f64| -> f64 {
// ∫ exp(logf0 + s (x − x0)) dx over [lo, hi], with infinite ends handled by the sign of s.
let _ = a;
let at = |x: f64| logf0 + s * (x - x0);
if s == 0.0 {
at(0.0).exp() * 0.0 + logf0.exp() * (hi - lo)
} else if hi.is_infinite() {
at(lo).exp() / -s
} else if lo.is_infinite() {
at(hi).exp() / s
} else if s > 0.0 {
at(hi).exp() * (1.0 - (-s * (hi - lo)).exp()) / s
} else {
at(lo).exp() * (1.0 - (s * (hi - lo)).exp()) / -s
}
};
// Left tail.
if self.x[0] > self.domain.0 {
if self.slope[0] <= 0.0 && self.domain.0.is_infinite() {
return Err(bad("the density is not log-concave or its left tail is too heavy: the slope of log f is not positive on the left"));
}
let a = area(0.0, self.domain.0, self.x[0], self.slope[0], self.x[0], self.logf[0]);
pieces.push((self.domain.0, self.x[0], 0, a));
total += a;
}
for i in 0..n {
let (hi_x, next) = if i + 1 < n { (self.x[i + 1], Some(i + 1)) } else { (self.domain.1, None) };
match next {
Some(j) => {
// Between the points the hat follows the lower of the two tangents.
let (s0, s1) = (self.slope[i], self.slope[j]);
let (t0, t1) = (self.logf[i] - s0 * self.x[i], self.logf[j] - s1 * self.x[j]);
let xi = if (s0 - s1).abs() < 1e-300 { 0.5 * (self.x[i] + self.x[j]) } else { ((t1 - t0) / (s0 - s1)).clamp(self.x[i], self.x[j]) };
let a1 = area(0.0, self.x[i], xi, s0, self.x[i], self.logf[i]);
let a2 = area(0.0, xi, self.x[j], s1, self.x[j], self.logf[j]);
pieces.push((self.x[i], xi, i, a1));
pieces.push((xi, self.x[j], j, a2));
total += a1 + a2;
}
None => {
if self.x[i] < self.domain.1 {
if self.slope[i] >= 0.0 && self.domain.1.is_infinite() {
return Err(bad("the density is not log-concave or its right tail is too heavy: the slope of log f is not negative on the right"));
}
let a = area(0.0, self.x[i], hi_x, self.slope[i], self.x[i], self.logf[i]);
pieces.push((self.x[i], hi_x, i, a));
total += a;
}
}
}
}
if !(total.is_finite() && total > 0.0) {
return Err(bad("the hat has no finite area"));
}
let mut acc = 0.0;
self.cumulative = pieces.iter().map(|p| { acc += p.3; acc }).collect();
self.pieces = pieces;
self.total = total;
Ok(())
}
/// The hat at `x`: `exp(logf_i + s_i (x − x_i))` for the tangent `i` of the piece holding `x`.
fn hat(&self, piece: usize, x: f64) -> f64 {
let (_, _, i, _) = self.pieces[piece];
(self.logf[i] + self.slope[i] * (x - self.x[i])).exp()
}
/// The area under the hat divided by the area under the density that it bounds: the expected
/// number of trials per variate is this ratio (`f` need only be proportional to the density,
/// so it is `total / ∫f`, estimated here by the ratio of the hat to its own squeeze: 1 if the
/// density is exactly exponential pieces). For a normalised density it is `total`.
pub fn hat_area(&self) -> f64 {
self.total
}
/// The number of construction points.
pub fn n_points(&self) -> usize {
self.x.len()
}
/// One variate. Rejected points tighten the hat while there is room (at most 200 points).
pub fn rvs_one<G: UniformGenerator>(&mut self, rng: &mut G) -> f64 {
loop {
// Choose a piece, then invert its exponential CDF.
let mut u = rng.next_f64() * self.total;
let piece = self.cumulative.partition_point(|&c| c <= u).min(self.pieces.len() - 1);
u -= if piece == 0 { 0.0 } else { self.cumulative[piece - 1] };
let (lo, hi, i, area) = self.pieces[piece];
let s = self.slope[i];
let v = (u / area).clamp(0.0, 1.0);
let x = if s == 0.0 {
lo + v * (hi - lo)
} else if hi.is_infinite() {
// Density ∝ exp(s (x − lo)) with s < 0: x = lo + ln(1 − v)/s.
lo + (1.0 - v).ln() / s
} else if lo.is_infinite() {
hi + (v.ln()) / s
} else {
// x = lo + ln(1 + v (e^{s (hi − lo)} − 1)) / s, written to avoid overflow.
let w = s * (hi - lo);
if s > 0.0 {
hi + (v + (1.0 - v) * (-w).exp()).ln() / s
} else {
lo + (1.0 + v * w.exp_m1()).ln() / s
}
};
let x = x.clamp(self.domain.0, self.domain.1);
let h = self.hat(piece, x);
let f = (self.pdf)(x);
if rng.next_f64() * h <= f {
return x;
}
if self.x.len() < self.max_points && f > 0.0 && f.is_finite() && self.insert(x).is_ok() {
let _ = self.rebuild();
}
}
}
pub fn rvs<G: UniformGenerator>(&mut self, n: usize, rng: &mut G) -> Vec<f64> {
(0..n).map(|_| self.rvs_one(rng)).collect()
}
}
/// Numerical inversion of a distribution function by cubic Hermite interpolation of its inverse
/// (SciPy's `NumericalInverseHermite`; Hörmann and Leydold's HINV). The interval `(a, b)` is
/// split until, on every piece, the cubic that matches `x` and `dx/du = 1/f(x)` at both ends
/// inverts `F` to within `u_resolution`: `|F(x̂(u)) − u| ≤ ε` at the middle of the piece. The
/// pieces are then a table, and a variate or a quantile costs a search and a cubic.
pub struct NumericalInverseHermite<'a> {
cdf: Box<dyn Fn(f64) -> f64 + 'a>,
/// Knots: `x`, `F(x)`, and `dx/du`.
x: Vec<f64>,
u: Vec<f64>,
d: Vec<f64>,
}
impl<'a> NumericalInverseHermite<'a> {
/// `cdf` and `pdf` on `domain` (infinite ends are cut where the tail probability is below
/// `u_resolution / 10`); `center` is a point inside the distribution (SciPy's `center`).
pub fn new(cdf: impl Fn(f64) -> f64 + 'a, pdf: impl Fn(f64) -> f64 + 'a, domain: (f64, f64), center: f64, u_resolution: f64) -> Result<Self, ErrorsJSL> {
if !matches!(domain.0.partial_cmp(&domain.1), Some(std::cmp::Ordering::Less)) || !(1e-15..=1e-3).contains(&u_resolution) {
return Err(bad("the domain must be a non-empty interval and the resolution between 1e-15 and 1e-3"));
}
let tail = 0.1 * u_resolution;
// Cut the tails.
let left = if domain.0.is_finite() {
domain.0
} else {
let (mut x, mut step) = (center, 1.0);
while cdf(x) > tail {
x -= step;
step *= 2.0;
if !x.is_finite() || step > 1e300 {
return Err(bad("the left tail does not decay"));
}
}
x
};
let right = if domain.1.is_finite() {
domain.1
} else {
let (mut x, mut step) = (center, 1.0);
while 1.0 - cdf(x) > tail {
x += step;
step *= 2.0;
if !x.is_finite() || step > 1e300 {
return Err(bad("the right tail does not decay"));
}
}
x
};
let density = |x: f64| pdf(x).max(f64::MIN_POSITIVE);
let (f_left, f_right) = (cdf(left), cdf(right));
// A first split into equal pieces in x, then recursive halving.
let mut knots: Vec<(f64, f64)> = vec![(left, f_left)];
let n0 = 20;
for k in 1..=n0 {
let x = left + (right - left) * k as f64 / n0 as f64;
knots.push((x, if k == n0 { f_right } else { cdf(x) }));
}
let mut done: Vec<(f64, f64)> = vec![knots[0]];
// Stack of intervals still to check, processed left to right.
let mut stack: Vec<((f64, f64), (f64, f64))> = (0..n0).rev().map(|k| (knots[k], knots[k + 1])).collect();
let mut guard = 0usize;
while let Some((a, b)) = stack.pop() {
guard += 1;
if guard > 2_000_000 {
return Err(bad("the interpolation does not converge: is the density continuous?"));
}
let (da, db) = (1.0 / density(a.0), 1.0 / density(b.0));
let h = b.1 - a.1;
let ok = if h <= 0.0 || b.0 - a.0 < 1e-14 * (1.0 + b.0.abs()) {
true
} else {
// Hermite value at the middle of the u-interval.
let t = 0.5;
let (h00, h10, h01, h11) = (2.0 * t * t * t - 3.0 * t * t + 1.0, t * t * t - 2.0 * t * t + t, -2.0 * t * t * t + 3.0 * t * t, t * t * t - t * t);
let xm = h00 * a.0 + h10 * h * da + h01 * b.0 + h11 * h * db;
let um = a.1 + t * h;
xm.is_finite() && xm >= a.0 && xm <= b.0 && (cdf(xm) - um).abs() <= 0.5 * u_resolution
};
if ok {
done.push(b);
} else {
let xm = 0.5 * (a.0 + b.0);
let m = (xm, cdf(xm));
stack.push((m, b));
stack.push((a, m));
}
}
let n = done.len();
let (x, u): (Vec<f64>, Vec<f64>) = done.into_iter().unzip();
let d: Vec<f64> = x.iter().map(|&xi| 1.0 / density(xi)).collect();
debug_assert_eq!(x.len(), n);
Ok(NumericalInverseHermite { cdf: Box::new(cdf), x, u, d })
}
/// The number of intervals of the table.
pub fn n_intervals(&self) -> usize {
self.x.len() - 1
}
/// The quantile function: `x` with `F(x) = u`, `0 ≤ u ≤ 1` (SciPy's `ppf`).
pub fn ppf(&self, u: f64) -> f64 {
if !(0.0..=1.0).contains(&u) {
return f64::NAN;
}
let u = u.clamp(self.u[0], *self.u.last().expect("knots"));
let k = self.u.partition_point(|&v| v <= u).saturating_sub(1).min(self.x.len() - 2);
let h = self.u[k + 1] - self.u[k];
if h <= 0.0 {
return self.x[k];
}
let t = (u - self.u[k]) / h;
let (h00, h10, h01, h11) = (2.0 * t * t * t - 3.0 * t * t + 1.0, t * t * t - 2.0 * t * t + t, -2.0 * t * t * t + 3.0 * t * t, t * t * t - t * t);
h00 * self.x[k] + h10 * h * self.d[k] + h01 * self.x[k + 1] + h11 * h * self.d[k + 1]
}
pub fn rvs_one<G: UniformGenerator>(&self, rng: &mut G) -> f64 {
self.ppf(rng.next_f64())
}
pub fn rvs<G: UniformGenerator>(&self, n: usize, rng: &mut G) -> Vec<f64> {
(0..n).map(|_| self.rvs_one(rng)).collect()
}
/// `n` variates by inversion of the first points of the (unscrambled, one-dimensional) Sobol
/// sequence (SciPy's `qrvs`); their empirical distribution function converges to `F` like
/// `(log n)/n`, not `n^{-1/2}`. The sequence starts at 0, which is skipped.
pub fn qrvs_sobol(&self, n: usize) -> Vec<f64> {
let mut sobol = SobolSequence::new(1).expect("one dimension");
sobol.next_point();
(0..n).map(|_| self.ppf(sobol.next_point()[0])).collect()
}
/// The largest `|F(ppf(u)) − u|` over `n` equally spaced values of `u` (SciPy's `u_error`,
/// which uses random ones).
pub fn u_error(&self, n: usize) -> f64 {
(0..n).map(|k| (k as f64 + 0.5) / n as f64).map(|u| ((self.cdf)(self.ppf(u)) - u).abs()).fold(0.0, f64::max)
}
}
/// The simple ratio-of-uniforms method (SciPy's `SimpleRatioUniforms`; Leydold's SROU) for a
/// unimodal density with a known mode: the region `0 < u ≤ √f(x)`, `v = (x − mode) u`, lies inside
/// the rectangle `[0, √f(mode)] × [v₋, v₊]` with `v₊ = sup_{x>mode} (x − mode) √f(x)` and `v₋ =
/// inf_{x<mode} (x − mode) √f(x)`. The two suprema are found numerically at construction (a scan
/// over geometrically spaced points, then golden-section refinement), so the density need not be
/// normalised and no derivative is needed.
pub struct SimpleRatioUniforms<'a> {
pdf: Box<dyn Fn(f64) -> f64 + 'a>,
mode: f64,
umax: f64,
vmin: f64,
vmax: f64,
domain: (f64, f64),
trials: u64,
accepted: u64,
}
/// The largest of `g(mode + sign·d)` over `d` in `(0, dmax]`, by a geometric scan and a golden
/// search around the best scan point.
fn scan_maximum(g: impl Fn(f64) -> f64, dmax: f64) -> f64 {
let mut best = (0.0f64, 0.0f64);
let mut d = dmax.min(1e12);
let hi = d;
let ratio = 1.05f64;
let mut points = Vec::new();
while d > hi * 1e-18 {
points.push(d);
d /= ratio;
}
if dmax.is_finite() && dmax < 1e12 {
// A finite end: also a uniform scan.
for k in 1..=2000 {
points.push(dmax * k as f64 / 2000.0);
}
}
for &d in &points {
let v = g(d);
if v.is_finite() && v > best.1 {
best = (d, v);
}
}
// Refine in the bracket of the best point.
let (mut lo, mut up) = (best.0 / ratio.powi(2), (best.0 * ratio.powi(2)).min(dmax));
for _ in 0..80 {
let (m1, m2) = (lo + (up - lo) * 0.381966, lo + (up - lo) * 0.618034);
if g(m1) < g(m2) {
lo = m1;
} else {
up = m2;
}
}
best.1.max(g(0.5 * (lo + up)))
}
impl<'a> SimpleRatioUniforms<'a> {
/// `pdf` (up to a constant) on `domain`, with its `mode`.
pub fn new(pdf: impl Fn(f64) -> f64 + 'a, mode: f64, domain: (f64, f64)) -> Result<Self, ErrorsJSL> {
if domain.0.is_nan() || domain.1.is_nan() || domain.0 > mode || mode > domain.1 || domain.0 >= domain.1 {
return Err(bad("the mode must lie inside the domain"));
}
let fm = pdf(mode);
if !(fm.is_finite() && fm > 0.0) {
return Err(bad("the density at the mode must be positive and finite"));
}
let up = |d: f64| d * pdf(mode + d).max(0.0).sqrt();
let down = |d: f64| d * pdf(mode - d).max(0.0).sqrt();
let vmax = if domain.1 > mode { scan_maximum(up, domain.1 - mode) } else { 0.0 };
let vmin = if domain.0 < mode { -scan_maximum(down, mode - domain.0) } else { 0.0 };
// A little room for the numerical search.
let (vmax, vmin) = (vmax * (1.0 + 1e-6), vmin * (1.0 + 1e-6));
if vmax.is_nan() || vmin.is_nan() || vmax <= vmin {
return Err(bad("the bounding rectangle is degenerate"));
}
Ok(SimpleRatioUniforms { pdf: Box::new(pdf), mode, umax: fm.sqrt() * (1.0 + 1e-12), vmin, vmax, domain, trials: 0, accepted: 0 })
}
/// The bounding rectangle `(umax, vmin, vmax)`.
pub fn bounds(&self) -> (f64, f64, f64) {
(self.umax, self.vmin, self.vmax)
}
/// The fraction of the points drawn so far that were kept.
pub fn acceptance_rate(&self) -> f64 {
if self.trials == 0 { f64::NAN } else { self.accepted as f64 / self.trials as f64 }
}
pub fn rvs_one<G: UniformGenerator>(&mut self, rng: &mut G) -> f64 {
loop {
self.trials += 1;
let u = rng.next_f64() * self.umax;
let v = self.vmin + rng.next_f64() * (self.vmax - self.vmin);
if u <= 0.0 {
continue;
}
let x = self.mode + v / u;
if x >= self.domain.0 && x <= self.domain.1 && u * u <= (self.pdf)(x) {
self.accepted += 1;
return x;
}
}
}
pub fn rvs<G: UniformGenerator>(&mut self, n: usize, rng: &mut G) -> Vec<f64> {
(0..n).map(|_| self.rvs_one(rng)).collect()
}
}
/// Numerical inversion of a distribution function from the density alone, by polynomial
/// interpolation of its inverse (SciPy's `NumericalInversePolynomial`; Derflinger, Hörmann and
/// Leydold's PINV). The interval is split until, on every piece, the polynomial of degree `order`
/// through `order + 1` Chebyshev-Lobatto points of the piece, as a function of the probability
/// mass, inverts the integral of the density to within `u_resolution` of the whole mass at
/// three interior test points. The masses are integrals of the density (adaptive Gauss-Legendre),
/// so the density needs neither normalising nor a distribution function.
pub struct NumericalInversePolynomial<'a> {
pdf: Box<dyn Fn(f64) -> f64 + 'a>,
rule: (Vec<f64>, Vec<f64>),
order: usize,
/// Interval ends in `x`, and the cumulative probability at each.
x: Vec<f64>,
u: Vec<f64>,
/// Per interval: the nodes `s_j` (probability within the interval, in [0, 1]) and the Newton
/// coefficients of `x(s)`, `order + 1` each.
nodes: Vec<f64>,
coef: Vec<f64>,
area: f64,
}
/// A piece of the table: its ends, its mass, the nodes in probability and the Newton coefficients.
type Piece = (f64, f64, f64, Vec<f64>, Vec<f64>);
/// Newton divided differences of `y` at the nodes `s`, in place.
fn divided_differences(s: &[f64], y: &mut [f64]) {
let n = s.len();
for j in 1..n {
for i in (j..n).rev() {
y[i] = (y[i] - y[i - 1]) / (s[i] - s[i - j]);
}
}
}
fn newton_eval(s: &[f64], c: &[f64], t: f64) -> f64 {
let mut v = c[c.len() - 1];
for j in (0..c.len() - 1).rev() {
v = v * (t - s[j]) + c[j];
}
v
}
impl<'a> NumericalInversePolynomial<'a> {
/// `pdf` (up to a constant) on `domain`; `order` is the degree of the polynomials (3 to 17,
/// SciPy's default is 5); infinite ends are cut where the mass of what is left is below
/// `u_resolution / 10` of the total. `center` is a point where the density is positive.
pub fn new(pdf: impl Fn(f64) -> f64 + 'a, domain: (f64, f64), center: f64, order: usize, u_resolution: f64) -> Result<Self, ErrorsJSL> {
if !matches!(domain.0.partial_cmp(&domain.1), Some(std::cmp::Ordering::Less)) || !(1e-15..=1e-5).contains(&u_resolution) || !(1..=17).contains(&order) {
return Err(bad("the domain must be a non-empty interval, the resolution between 1e-15 and 1e-5 and the order between 1 and 17"));
}
let rule = gauss_legendre(12);
let pdfb: Box<dyn Fn(f64) -> f64 + 'a> = Box::new(pdf);
let f = |x: f64| pdfb(x).max(0.0);
// The effective domain.
let (mut lo, mut hi) = (domain.0.max(center - 1.0), domain.1.min(center + 1.0));
if lo >= hi {
lo = domain.0.max(center - 1.0).min(center);
hi = domain.1.min(center + 1.0).max(center);
}
let mut total = integrate(&f, &rule, lo, hi);
let mut grow = 1.0;
while total <= 0.0 && (lo > domain.0 || hi < domain.1) && grow < 1e30 {
grow *= 4.0;
lo = domain.0.max(center - grow);
hi = domain.1.min(center + grow);
total = integrate(&f, &rule, lo, hi);
}
if !(total > 0.0 && total.is_finite()) {
return Err(bad("the density has no mass near the centre"));
}
let tail = 0.1 * u_resolution;
let mut step = (hi - lo).max(1.0);
while hi < domain.1 {
let next = if domain.1.is_finite() { (hi + step).min(domain.1) } else { hi + step };
let m = integrate(&f, &rule, hi, next);
total += m;
hi = next;
if m <= tail * total {
break;
}
step *= 2.0;
if !hi.is_finite() || step > 1e300 {
return Err(bad("the right tail does not decay"));
}
}
step = (hi - lo).max(1.0) * 0.5;
while lo > domain.0 {
let next = if domain.0.is_finite() { (lo - step).max(domain.0) } else { lo - step };
let m = integrate(&f, &rule, next, lo);
total += m;
lo = next;
if m <= tail * total {
break;
}
step *= 2.0;
if !lo.is_finite() || step > 1e300 {
return Err(bad("the left tail does not decay"));
}
}
// Splitting.
let cheb = |k: usize| -> Vec<f64> { (0..=k).map(|j| 0.5 * (1.0 - (std::f64::consts::PI * j as f64 / k as f64).cos())).collect() };
let unit = cheb(order);
let mut stack: Vec<(f64, f64)> = {
let n0 = 16;
(0..n0).rev().map(|k| (lo + (hi - lo) * k as f64 / n0 as f64, lo + (hi - lo) * (k + 1) as f64 / n0 as f64)).collect()
};
let mut pieces: Vec<Piece> = Vec::new();
let mut guard = 0usize;
while let Some((a, b)) = stack.pop() {
guard += 1;
if guard > 400_000 {
return Err(bad("the interpolation does not converge: is the density continuous?"));
}
let xs: Vec<f64> = unit.iter().map(|&t| a + (b - a) * t).collect();
let mut cum = vec![0.0; xs.len()];
for j in 1..xs.len() {
cum[j] = cum[j - 1] + integrate(&f, &rule, xs[j - 1], xs[j]);
}
let mass = cum[order];
if mass <= 1e-3 * tail * total {
// Negligible mass: a straight line.
pieces.push((a, b, mass, vec![0.0, 1.0], vec![a, b - a]));
continue;
}
let s: Vec<f64> = cum.iter().map(|&c| c / mass).collect();
let mut c = xs.clone();
if s.windows(2).any(|w| w[1].is_nan() || w[1] <= w[0]) {
if b - a < 1e-13 * (1.0 + b.abs()) {
pieces.push((a, b, mass, vec![0.0, 1.0], vec![a, b - a]));
} else {
let m = 0.5 * (a + b);
stack.push((m, b));
stack.push((a, m));
}
continue;
}
divided_differences(&s, &mut c);
let mut ok = b - a < 1e-13 * (1.0 + b.abs());
if !ok {
ok = true;
for &t in &[0.17, 0.5, 0.83] {
let xh = newton_eval(&s, &c, t);
if !(xh >= a && xh <= b) {
ok = false;
break;
}
let err = (integrate(&f, &rule, a, xh) - t * mass).abs();
if err > 0.5 * u_resolution * total {
ok = false;
break;
}
}
}
if ok {
pieces.push((a, b, mass, s, c));
} else {
let m = 0.5 * (a + b);
stack.push((m, b));
stack.push((a, m));
}
}
let area: f64 = pieces.iter().map(|p| p.2).sum();
let (mut x, mut u, mut nodes, mut coef) = (vec![pieces[0].0], vec![0.0], Vec::new(), Vec::new());
let mut acc = 0.0;
for (_, b, mass, s, c) in pieces {
acc += mass;
x.push(b);
u.push(acc / area);
// Pad to a fixed width so the intervals index uniformly.
let w = order + 1;
let mut sp = s.clone();
let mut cp = c.clone();
sp.resize(w, 0.0);
cp.resize(w, 0.0);
nodes.extend(sp);
coef.extend(cp);
}
*u.last_mut().expect("pieces") = 1.0;
Ok(NumericalInversePolynomial { pdf: pdfb, rule, order, x, u, nodes, coef, area })
}
/// The number of intervals.
pub fn n_intervals(&self) -> usize {
self.x.len() - 1
}
/// The integral of the density over the domain (the normalising constant).
pub fn area(&self) -> f64 {
self.area
}
/// The quantile function: `x` with `F(x) = u`.
pub fn ppf(&self, u: f64) -> f64 {
if !(0.0..=1.0).contains(&u) {
return f64::NAN;
}
let k = self.u.partition_point(|&v| v <= u).saturating_sub(1).min(self.x.len() - 2);
let h = self.u[k + 1] - self.u[k];
let t = if h > 0.0 { ((u - self.u[k]) / h).clamp(0.0, 1.0) } else { 0.0 };
let w = self.order + 1;
// Pieces with a straight line carry two nodes and zero padding after them.
let (s, c) = (&self.nodes[k * w..(k + 1) * w], &self.coef[k * w..(k + 1) * w]);
let used = if s[1] == 1.0 && s[2..].iter().all(|&v| v == 0.0) && c[2..].iter().all(|&v| v == 0.0) { 2 } else { w };
newton_eval(&s[..used], &c[..used], t).clamp(self.x[k], self.x[k + 1])
}
/// The distribution function, by integrating the density from the start of the interval.
pub fn cdf(&self, x: f64) -> f64 {
if x <= self.x[0] {
return 0.0;
}
if x >= *self.x.last().expect("knots") {
return 1.0;
}
let k = self.x.partition_point(|&v| v <= x).saturating_sub(1).min(self.x.len() - 2);
let f = |t: f64| (self.pdf)(t).max(0.0);
(self.u[k] + integrate(&f, &self.rule, self.x[k], x) / self.area).clamp(0.0, 1.0)
}
pub fn rvs_one<G: UniformGenerator>(&self, rng: &mut G) -> f64 {
self.ppf(rng.next_f64())
}
pub fn rvs<G: UniformGenerator>(&self, n: usize, rng: &mut G) -> Vec<f64> {
(0..n).map(|_| self.rvs_one(rng)).collect()
}
/// `n` variates by inversion of the (unscrambled, one-dimensional) Sobol sequence.
pub fn qrvs_sobol(&self, n: usize) -> Vec<f64> {
let mut sobol = SobolSequence::new(1).expect("one dimension");
sobol.next_point();
(0..n).map(|_| self.ppf(sobol.next_point()[0])).collect()
}
/// The largest `|F(ppf(u)) − u|` over `n` equally spaced values of `u`.
pub fn u_error(&self, n: usize) -> f64 {
(0..n).map(|k| (k as f64 + 0.5) / n as f64).map(|u| (self.cdf(self.ppf(u)) - u).abs()).fold(0.0, f64::max)
}
}
/// Fast numerical inversion of a standard density with a location and a scale (SciPy's
/// `FastGeneratorInversion`, which wraps the library's distributions and picks the method that
/// suits each; here the density is given, and the method is polynomial inversion of order 5 at
/// resolution `1e-12`): `X = loc + scale · Z`, `Z` with the given density.
pub struct FastGeneratorInversion<'a> {
inner: NumericalInversePolynomial<'a>,
loc: f64,
scale: f64,
}
impl<'a> FastGeneratorInversion<'a> {
pub fn new(pdf: impl Fn(f64) -> f64 + 'a, domain: (f64, f64), center: f64, loc: f64, scale: f64) -> Result<Self, ErrorsJSL> {
if !(scale > 0.0 && scale.is_finite() && loc.is_finite()) {
return Err(bad("the scale must be positive and finite, the location finite"));
}
Ok(FastGeneratorInversion { inner: NumericalInversePolynomial::new(pdf, domain, center, 5, 1e-12)?, loc, scale })
}
/// The support of `X`.
pub fn support(&self) -> (f64, f64) {
(self.loc + self.scale * self.inner.x[0], self.loc + self.scale * self.inner.x[self.inner.x.len() - 1])
}
pub fn ppf(&self, u: f64) -> f64 {
self.loc + self.scale * self.inner.ppf(u)
}
pub fn cdf(&self, x: f64) -> f64 {
self.inner.cdf((x - self.loc) / self.scale)
}
pub fn rvs<G: UniformGenerator>(&self, n: usize, rng: &mut G) -> Vec<f64> {
(0..n).map(|_| self.ppf(rng.next_f64())).collect()
}
pub fn qrvs_sobol(&self, n: usize) -> Vec<f64> {
self.inner.qrvs_sobol(n).into_iter().map(|z| self.loc + self.scale * z).collect()
}
pub fn u_error(&self, n: usize) -> f64 {
self.inner.u_error(n)
}
}
TransformedDensityRejection::new(pdf, dpdf, domain, center)takes the density and its derivative (not of its logarithm), the interval and a point near the mode. The density need not be normalised. A density that is visibly not log-concave at the construction points is refused. Between them log-concavity is assumed, as in UNU.RAN.NumericalInverseHermite::new(cdf, pdf, domain, center, u_resolution);ppfgives the quantile function,rvsthe variates andu_errorthe measured error.qrvs_sobolonNumericalInverseHermiteandDiscreteGuideTableturns the first points of a Sobol sequence into variates (SciPy’sqrvs): inversion keeps the low discrepancy of the sequence, which rejection cannot. The 4096 variates of the standard normal that it gives have a Kolmogorov-Smirnov distance below from the normal distribution, against about for as many random ones.MultivariateRatioUniforms::new(pdf, mode)samples a unimodal density in any dimension (a correlated normal in 3-D reproduces its mean and covariance and its marginals pass Kolmogorov-Smirnov tests);SimpleRatioUniforms::new(pdf, mode, domain)needs the mode;NumericalInversePolynomial::new(pdf, domain, center, order, u_resolution)needs only the density (ppf,cdf,rvs,qrvs_sobol,u_error,area);FastGeneratorInversion::new(pdf, domain, center, loc, scale)is its order-5, form withppf,cdf,rvsandsupport, andlib_jsl_statistics::distributions::fast_generator_inversion(&dist)builds one from any distribution object (the centre is its median). SciPy’sFastGeneratorInversionchooses its own method for each distribution; here it is always polynomial inversion. The other UNU.RAN generators are not implemented.- Discrete distributions are given by a probability vector over , not by a SciPy distribution object.
In practice
The numerical inversion is compared with SciPy’s NumericalInverseHermite (book/generator/data/make_smp230_refs.py), both at the resolution : the number of intervals, the largest u-error over a grid, and the largest error of the quantile function against the exact one over 999 probabilities.
Table 9.5. Hermite inversion against SciPy's.
| Distribution | Intervals, library / SciPy | Largest u-error, library / SciPy | Largest quantile error (relative above 1), library / SciPy |
|---|---|---|---|
norm | 4001 / 3000 | 5.0e-13 / 9.1e-13 | 1.0e-11 / 1.3e-11 |
gamma 2.5 | 3644 / 2927 | 5.0e-13 / 9.7e-13 | 2.2e-11 / 1.7e-11 |
beta 2.5 1.5 | 2882 / 2458 | 5.0e-13 / 9.0e-13 | 2.9e-12 / 4.2e-12 |
expon | 2472 / 2033 | 5.0e-13 / 9.0e-13 | 5.4e-12 / 2.3e-11 |
lognorm 0.5 | 4017 / 3373 | 5.0e-13 / 9.3e-13 | 1.6e-11 / 1.4e-11 |
The library’s table has 17–33 % more intervals, because it halves each interval until the criterion at its middle is met with a tolerance of , which brings its largest u-error to half the resolution (, against SciPy’s ). The quantile functions agree with the exact ones to about in both.
Polynomial inversion is compared in the same way with NumericalInversePolynomial at order 5 (book/generator/data/make_smp234_refs.py); the library is given only the density:
Table 9.5b. Polynomial inversion against SciPy's.
| Distribution | Intervals, library / SciPy | Largest u-error, library / SciPy | Largest quantile error (relative above 1), library / SciPy |
|---|---|---|---|
norm | 428 / 252 | 5.0e-13 / 9.1e-13 | 1.8e-12 / 4.5e-11 |
gamma 2.5 | 375 / 251 | 4.7e-13 / 9.0e-13 | 1.0e-11 / 3.6e-11 |
beta 2.5 1.5 | 311 / 203 | 4.9e-13 / 9.0e-13 | 2.3e-12 / 3.0e-12 |
expon | 245 / 156 | 5.0e-13 / 8.1e-13 | 2.2e-11 / 4.8e-11 |
lognorm 0.5 | 405 / 262 | 5.0e-13 / 1.2e-12 | 2.2e-11 / 2.8e-11 |
t 5 | 405 / 287 | 4.9e-13 / 9.0e-13 | 1.3e-11 / 5.1e-11 |
The library’s tables have about 50 % more intervals than SciPy’s, again because the acceptance test is stricter (three points, ), and its u-error is about half of SciPy’s. The samplers are checked by their output. The Kolmogorov-Smirnov distance of 200,000 variates from the exact distribution function, against the 5 % critical value :
Table 9.6. Goodness of fit of the continuous samplers.
| Sampler and distribution | KS distance, 200,000 variates | 5 % critical value | Test | Set-up |
|---|---|---|---|---|
| transformed density rejection, normal | 0.0014 | 0.0036 | passes | 100 construction points |
| transformed density rejection, gamma(3) | 0.0011 | 0.0036 | passes | 100 construction points |
| transformed density rejection, beta(2, 3) | 0.0020 | 0.0036 | passes | 100 construction points |
| Hermite inversion, gamma(3) | 0.0020 | 0.0036 | passes | 3670 intervals |
| ratio of uniforms, normal | 0.0032 | 0.0036 | passes | acceptance ≈ 73 % |
and the simple ratio of uniforms, polynomial inversion and the fast generator:
Table 9.6b. Goodness of fit of the 2.34 samplers.
| Sampler and distribution | KS distance, 200,000 variates | 5 % critical value | Test | Set-up |
|---|---|---|---|---|
| simple ratio of uniforms, normal | 0.0031 | 0.0036 | passes | acceptance 73 % |
| simple ratio of uniforms, gamma(3) | 0.0015 | 0.0036 | passes | acceptance 72 % |
| simple ratio of uniforms, beta(2, 3) | 0.0022 | 0.0036 | passes | acceptance 68 % |
| polynomial inversion, gamma(3) | 0.0020 | 0.0036 | passes | 382 intervals |
| fast generator inversion, normal(3, 2) | 0.0015 | 0.0036 | passes | u-error 5.0e-13 |
and a chi-square test of the two discrete samplers on a Poisson(5) distribution truncated at 20:
Table 9.7. Goodness of fit of the discrete samplers.
| Sampler (Poisson(5) truncated at 20) | Chi-square statistic | Degrees of freedom | p-value |
|---|---|---|---|
| alias method | 20.4 | 20 | 0.43 |
| guide table | 17.5 | 20 | 0.62 |
All the tests are passed, at a single seed. They show that the samplers are not grossly wrong, not that they are exact: for that, the properties of the construction (the hat bounds the density at every construction point and between them, by concavity) and the unit tests, which repeat these checks with other seeds and densities, are the evidence.
Strengths
- One interface for any distribution with an evaluable density or distribution function.
- Exact rejection and alias sampling, with a hat that adapts to the density.
- Inversion to a chosen resolution, with the quantile function as a by-product, so that the variates can be generated by quasi-random sequences or antithetic pairs.
Weaknesses
- Rejection needs log-concavity, which is checked only at the construction points.
- Inversion needs the distribution function as well as the density, and an interval or tails that can be cut.
- Polynomial inversion integrates the density numerically, which is slower to set up than Hermite inversion when a distribution function is available, and it assumes a density continuous enough for the interpolation to converge. The simple ratio of uniforms accepts about 70 %. None of the generators handles multivariate densities.
Exercises
- Show that the alias method returns outcome with probability .
- Show that the expected number of trials of transformed density rejection is the area under the hat divided by the area under .
- Prove that if is concave then the minimum of its tangent lines lies above it.
- Show that the ratio-of-uniforms region for the standard normal density is bounded by and , and find the probability that a point of the rectangle is accepted.
- Why does the Hermite cubic through and with the slopes and have an error of order for smooth ?
- A density is log-concave on but has slope at a construction point and the domain is infinite on the right. What goes wrong with the tail of the hat?
Hints and answers
- Each column has probability . Outcome gets from the column that holds it, where is the value left after the pairings, and from each column that has as its alias. Each pairing that makes an alias lowered its value by exactly , so (the value it started with), and the total for is .
- Each trial draws from the density and accepts with probability . The probability of acceptance per trial is , and the number of trials until the first acceptance is geometric with that mean’s reciprocal.
- for every and every , by concavity, so is below each tangent and hence below their minimum; exponentiate.
- , and , whose maximum is at . The region’s area is and the rectangle’s is , so the acceptance probability is .
- The cubic Hermite interpolant of a function with four continuous derivatives on an interval of length has error at most . Here , whose fourth derivative with respect to is finite where is positive and smooth, and is the interval’s length in , which is about .
- The tangent there is horizontal, so the hat is constant to the right of that point and its area is infinite: the construction must continue outward until the slope is negative.
Further reading
- A. J. Walker, “New fast method for generating discrete random numbers with arbitrary frequency distributions”, Electronics Letters 10 (1974) 127–128; “An efficient method for generating discrete random variables with general distributions”, ACM Transactions on Mathematical Software 3 (1977) 253–256.
- M. D. Vose, “A linear algorithm for generating random numbers with a given distribution”, IEEE Transactions on Software Engineering 17 (1991) 972–975.
- W. R. Gilks and P. Wild, “Adaptive rejection sampling for Gibbs sampling”, Applied Statistics 41 (1992) 337–348.
- W. Hörmann, “A rejection technique for sampling from T-concave distributions”, ACM Transactions on Mathematical Software 21 (1995) 182–193.
- A. J. Kinderman and J. F. Monahan, “Computer generation of random variables using the ratio of uniform deviates”, ACM Transactions on Mathematical Software 3 (1977) 257–260.
- W. Hörmann and J. Leydold, “Continuous random variate generation by fast numerical inversion”, ACM Transactions on Mathematical Software 29 (2003) 405–420.
- W. Hörmann, J. Leydold and G. Derflinger, Automatic Nonuniform Random Variate Generation, Springer, 2004.