Skip to main content

lib_jsl_random/distributions/
binomial.rs

1use crate::{distributions::beta::beta_distribution, uniform_generator::UniformGenerator};
2use lib_jsl_core::ErrorsJSL;
3
4/// Inversion by sequential search of the pmf, starting from zero (expected cost O(np)).
5fn binomial_inversion<U: UniformGenerator>(rng: &mut U, n: u64, p: f64) -> u64 {
6    let q = 1.0 - p;
7    let ratio = p / q;
8    let mut pmf = q.powf(n as f64);
9    let mut cdf = pmf;
10    let u = rng.next_f64();
11    let mut k = 0;
12    while u > cdf && k < n {
13        pmf *= ratio * (n - k) as f64 / (k + 1) as f64;
14        k += 1;
15        cdf += pmf;
16    }
17    k
18}
19
20/// A binomial sample: the number of successes in `n` independent trials of probability `p`.
21///
22/// Small `n·min(p, 1−p)` uses inversion; otherwise Knuth's recursive beta splitting reduces the
23/// problem exactly: with `a = 1 + ⌊n/2⌋`, the `a`-th order statistic of `n` uniforms is
24/// `X ~ Beta(a, n + 1 − a)`, and the count below `p` follows from one smaller binomial on the
25/// side of `X` that contains `p`. Cost is `O(log n)` beta samples.
26pub fn binomial_distribution<U: UniformGenerator>(uniform_generator: &mut U, n: u64, p: f64) -> Result<u64, ErrorsJSL> {
27    if !(0.0..=1.0).contains(&p) {
28        return Err(ErrorsJSL::InvalidInputRange("p must lie in [0, 1]"));
29    }
30    let (mut n, mut p) = (n, p);
31    let mut offset = 0;
32    loop {
33        if n == 0 || p == 0.0 {
34            return Ok(offset);
35        }
36        if p == 1.0 {
37            return Ok(offset + n);
38        }
39        if (n as f64) * p.min(1.0 - p) < 20.0 {
40            // Inversion is cheapest from the side with the smaller mean.
41            return Ok(if p <= 0.5 {
42                offset + binomial_inversion(uniform_generator, n, p)
43            } else {
44                offset + n - binomial_inversion(uniform_generator, n, 1.0 - p)
45            });
46        }
47        let a = 1 + n / 2;
48        let b = n + 1 - a;
49        let x = beta_distribution(uniform_generator, a as f64, b as f64)?;
50        if x >= p {
51            // Fewer than a successes: the a − 1 uniforms below X are uniform on [0, X).
52            n = a - 1;
53            p /= x;
54        } else {
55            // At least a successes: a fixed, the b − 1 above X are uniform on (X, 1].
56            offset += a;
57            n = b - 1;
58            p = (p - x) / (1.0 - x);
59        }
60    }
61}
62
63#[cfg(test)]
64mod tests {
65    use super::*;
66    use crate::uniform_generator::UniformRNG;
67
68    #[test]
69    fn mean_and_variance_match_np_and_npq_in_both_regimes() {
70        let mut rng = UniformRNG::from_seed(2);
71        for (n, p) in [(10u64, 0.3), (40, 0.9), (1000, 0.4), (1_000_000, 0.01), (5000, 0.73)] {
72            let m = 40_000;
73            let s: Vec<f64> = (0..m).map(|_| binomial_distribution(&mut rng, n, p).unwrap() as f64).collect();
74            let mean = s.iter().sum::<f64>() / m as f64;
75            let var = s.iter().map(|v| (v - mean).powi(2)).sum::<f64>() / (m - 1) as f64;
76            let (em, ev) = (n as f64 * p, n as f64 * p * (1.0 - p));
77            assert!((mean - em).abs() < 5.0 * (ev / m as f64).sqrt(), "n={n} p={p}: mean {mean} vs {em}");
78            assert!((var / ev - 1.0).abs() < 0.04, "n={n} p={p}: var {var} vs {ev}");
79            assert!(s.iter().all(|&v| v <= n as f64));
80        }
81    }
82
83    #[test]
84    fn small_case_frequencies_match_the_pmf_and_edges() {
85        let mut rng = UniformRNG::from_seed(9);
86        let (n, p, m) = (4u64, 0.35, 200_000);
87        let mut counts = [0usize; 5];
88        (0..m).for_each(|_| counts[binomial_distribution(&mut rng, n, p).unwrap() as usize] += 1);
89        let pmf = |k: u64| [1.0, 4.0, 6.0, 4.0, 1.0][k as usize] * p.powi(k as i32) * (1.0 - p).powi((n - k) as i32);
90        for k in 0..=n {
91            assert!((counts[k as usize] as f64 / m as f64 - pmf(k)).abs() < 0.004, "k={k}");
92        }
93        assert_eq!(binomial_distribution(&mut rng, 7, 0.0).unwrap(), 0);
94        assert_eq!(binomial_distribution(&mut rng, 7, 1.0).unwrap(), 7);
95        assert!(binomial_distribution(&mut rng, 7, 1.5).is_err());
96    }
97}