Skip to main content

lib_jsl_random/distributions/
poisson.rs

1//! Poisson random variables.
2
3use crate::distributions::binomial::binomial_distribution;
4use crate::distributions::gamma::gamma_distribution;
5use crate::uniform_generator::UniformGenerator;
6
7/// Knuth's multiplication method: the number of uniforms whose running product stays above `e^{−λ}`.
8/// Expected cost `λ + 1` uniforms; used for small `λ`.
9fn poisson_small<U: UniformGenerator>(rng: &mut U, lambda: f64) -> u64 {
10    let limit = (-lambda).exp();
11    let mut product = rng.next_f64();
12    let mut k = 0;
13    while product > limit {
14        product *= rng.next_f64();
15        k += 1;
16    }
17    k
18}
19
20// ANCHOR: poisson
21/// A Poisson(`lambda`) sample (returned as `f64`), for `lambda ≥ 0`.
22///
23/// Small `λ` (below 16) uses Knuth's multiplication method, a fresh uniform per step. Larger `λ`
24/// use the exact recursion of Ahrens and Dieter (Knuth, *TAOCP* 3.4.1): with `m = ⌊7λ/8⌋` and
25/// `G ~ Gamma(m, 1)` (the time of the `m`-th event of a unit-rate Poisson process), the count is
26/// `m + Poisson(λ − G)` if `G < λ`, and `Binomial(m − 1, λ/G)` otherwise, so the cost grows only
27/// logarithmically in `λ`. (An earlier version reused one uniform throughout, with its loop
28/// condition inverted, and returned −1 for every `λ`.) Returns `NaN` for negative or NaN `λ`.
29pub fn poisson_distribution_knuth<U>(uniform_generator: &mut U, lambda: f64) -> f64
30where
31    U: UniformGenerator,
32{
33    if lambda.is_nan() || lambda < 0.0 || lambda.is_infinite() {
34        return f64::NAN;
35    }
36    let (mut lambda, mut offset) = (lambda, 0u64);
37    while lambda >= 16.0 {
38        let m = (0.875 * lambda).floor() as u64;
39        let g = gamma_distribution(uniform_generator, m as f64, 1.0).expect("m ≥ 14 is a valid shape");
40        if g < lambda {
41            offset += m;
42            lambda -= g;
43        } else {
44            let b = binomial_distribution(uniform_generator, m - 1, lambda / g).expect("λ/G lies in [0, 1]");
45            return (offset + b) as f64;
46        }
47    }
48    (offset + poisson_small(uniform_generator, lambda)) as f64
49}
50// ANCHOR_END: poisson
51
52#[cfg(test)]
53mod tests {
54    use super::*;
55    use crate::uniform_generator::UniformRNG;
56
57    #[test]
58    fn mean_and_variance_equal_lambda() {
59        // The old sampler returned −1 for every λ.
60        let mut rng = UniformRNG::from_seed(3);
61        for lambda in [0.3, 4.0, 15.9, 16.0, 120.0, 5000.0] {
62            let n = 100_000;
63            let s: Vec<f64> = (0..n).map(|_| poisson_distribution_knuth(&mut rng, lambda)).collect();
64            let mean = s.iter().sum::<f64>() / n as f64;
65            let var = s.iter().map(|x| (x - mean).powi(2)).sum::<f64>() / n as f64;
66            let tol = 5.0 * (lambda / n as f64).sqrt();
67            assert!((mean - lambda).abs() < tol, "λ = {lambda}: mean {mean}");
68            assert!((var / lambda - 1.0).abs() < 0.03, "λ = {lambda}: variance {var}");
69            assert!(s.iter().all(|&x| x >= 0.0 && x == x.floor()));
70        }
71        assert_eq!(poisson_distribution_knuth(&mut rng, 0.0), 0.0);
72        assert!(poisson_distribution_knuth(&mut rng, -1.0).is_nan());
73    }
74
75    #[test]
76    fn small_lambda_probabilities() {
77        // P(0) = e^{-λ}, P(1) = λ e^{-λ}.
78        let mut rng = UniformRNG::from_seed(4);
79        let lambda = 1.5;
80        let n = 200_000;
81        let s: Vec<f64> = (0..n).map(|_| poisson_distribution_knuth(&mut rng, lambda)).collect();
82        let p0 = s.iter().filter(|&&x| x == 0.0).count() as f64 / n as f64;
83        let p1 = s.iter().filter(|&&x| x == 1.0).count() as f64 / n as f64;
84        assert!((p0 - (-lambda).exp()).abs() < 0.004 && (p1 - lambda * (-lambda).exp()).abs() < 0.004, "{p0} {p1}");
85    }
86}