Skip to main content

lib_jsl_special_functions/
inverse_incomplete.rs

1//! Inverses of the regularized incomplete gamma and beta functions (SciPy's `gammaincinv`,
2//! `gammainccinv` and `betaincinv`): an initial approximation, then Halley's method on the
3//! function itself, whose first two derivatives are known in closed form.
4//!
5//! See the book entry [Log-domain functions and inverse incomplete integrals](https://jwkunz.github.io/lib_jsl/book/special_functions/log-domain.html#inverting-the-incomplete-gamma-and-beta-functions).
6
7use crate::gamma::ln_gamma;
8use crate::incomplete_beta::incomplete_beta;
9use crate::incomplete_gamma::{incomplete_gamma, incomplete_gamma_upper};
10
11/// The Abramowitz-Stegun 26.2.22 approximation to the normal quantile of `1 − pp`, `pp ≤ 1/2`.
12fn normal_guess(pp: f64) -> f64 {
13    let t = (-2.0 * pp.ln()).sqrt();
14    t - (2.30753 + t * 0.27061) / (1.0 + t * (0.99229 + t * 0.04481))
15}
16
17// ANCHOR: gammaincinv
18/// The `x ≥ 0` with `P(a, x) = p` (SciPy's `gammaincinv`). The start is the Wilson-Hilferty
19/// approximation for `a > 1` and the small-`x` series for `a ≤ 1`; then Halley steps
20/// `x ← x − u / (1 − ½ u ((a−1)/x − 1))` with `u = (P − p)/P'` and `P' = x^{a−1} e^{−x} / Γ(a)`.
21pub fn gammaincinv(a: f64, p: f64) -> f64 {
22    invert_gamma(a, p, false)
23}
24// ANCHOR_END: gammaincinv
25
26/// The `x ≥ 0` with `Q(a, x) = 1 − P(a, x) = q` (SciPy's `gammainccinv`). Both inverses iterate
27/// on the smaller of the two tails, `P` or `Q`, which is computed with full relative accuracy;
28/// the other target is formed exactly, since `1 − t` is exact for `t ∈ [½, 1]`.
29pub fn gammainccinv(a: f64, q: f64) -> f64 {
30    invert_gamma(a, q, true)
31}
32
33fn invert_gamma(a: f64, target: f64, upper: bool) -> f64 {
34    if !(a > 0.0) || !(0.0..=1.0).contains(&target) {
35        return f64::NAN;
36    }
37    if target > 0.5 {
38        return invert_gamma(a, 1.0 - target, !upper);
39    }
40    let p = if upper { 1.0 - target } else { target };
41    if (upper && target == 1.0) || (!upper && target == 0.0) {
42        return 0.0;
43    }
44    if (upper && target == 0.0) || (!upper && target == 1.0) {
45        return f64::INFINITY;
46    }
47    let gln = ln_gamma(a);
48    let mut x = if a > 1.0 {
49        let small = if upper { target } else { p }; // the tail probability nearer 0
50        let z = if p < 0.5 { -normal_guess(small.min(1.0 - small).max(f64::MIN_POSITIVE)) } else { normal_guess(if upper { target } else { 1.0 - p }) };
51        (a * (1.0 - 1.0 / (9.0 * a) + z / (3.0 * a.sqrt())).powi(3)).max(1e-3)
52    } else {
53        let t = 1.0 - a * (0.253 + a * 0.12);
54        if p < t { (p / t).powf(1.0 / a) } else { 1.0 - (-(p - t) / (1.0 - t)).ln_1p() }
55    };
56    for _ in 0..100 {
57        if x <= 0.0 {
58            return 0.0;
59        }
60        let err = if upper { target - incomplete_gamma_upper(a, x) } else { incomplete_gamma(a, x) - target };
61        let dp = ((a - 1.0) * x.ln() - x - gln).exp();
62        if dp == 0.0 {
63            break;
64        }
65        let u = err / dp;
66        let step = u / (1.0 - 0.5 * (u * ((a - 1.0) / x - 1.0)).min(1.0));
67        let next = x - step;
68        x = if next <= 0.0 { 0.5 * x } else { next };
69        if step.abs() <= 1e-15 * x {
70            break;
71        }
72    }
73    x
74}
75
76// ANCHOR: betaincinv
77/// The `x ∈ [0, 1]` with `I_x(a, b) = p` (SciPy's `betaincinv`). The start is the normal-based
78/// approximation of Abramowitz and Stegun 26.5.22 for `a, b ≥ 1` and the small-`x` and
79/// small-`1 − x` power laws otherwise; then Halley steps with
80/// `I' = x^{a−1}(1−x)^{b−1} / B(a, b)`.
81pub fn betaincinv(a: f64, b: f64, p: f64) -> f64 {
82    if !(a > 0.0) || !(b > 0.0) || !(0.0..=1.0).contains(&p) {
83        return f64::NAN;
84    }
85    if p == 0.0 || p == 1.0 {
86        return p;
87    }
88    let mut x = if a >= 1.0 && b >= 1.0 {
89        let pp = if p < 0.5 { p } else { 1.0 - p };
90        let mut z = normal_guess(pp);
91        if p < 0.5 {
92            z = -z;
93        }
94        let al = (z * z - 3.0) / 6.0;
95        let h = 2.0 / (1.0 / (2.0 * a - 1.0) + 1.0 / (2.0 * b - 1.0));
96        let w = z * (al + h).sqrt() / h - (1.0 / (2.0 * b - 1.0) - 1.0 / (2.0 * a - 1.0)) * (al + 5.0 / 6.0 - 2.0 / (3.0 * h));
97        a / (a + b * (2.0 * w).exp())
98    } else {
99        let lna = (a / (a + b)).ln();
100        let lnb = (b / (a + b)).ln();
101        let t = (a * lna).exp() / a;
102        let u = (b * lnb).exp() / b;
103        let w = t + u;
104        if p < t / w { (a * w * p).powf(1.0 / a) } else { 1.0 - (b * w * (1.0 - p)).powf(1.0 / b) }
105    };
106    let afac = ln_gamma(a + b) - ln_gamma(a) - ln_gamma(b);
107    for j in 0..100 {
108        if x <= 0.0 || x >= 1.0 {
109            return x.clamp(0.0, 1.0);
110        }
111        let err = incomplete_beta(a, b, x) - p;
112        let dp = ((a - 1.0) * x.ln() + (b - 1.0) * (-x).ln_1p() + afac).exp();
113        if dp == 0.0 {
114            break;
115        }
116        let u = err / dp;
117        let t = u / (1.0 - 0.5 * (u * ((a - 1.0) / x - (b - 1.0) / (1.0 - x))).min(1.0));
118        let mut next = x - t;
119        if next <= 0.0 {
120            next = 0.5 * x;
121        }
122        if next >= 1.0 {
123            next = 0.5 * (x + 1.0);
124        }
125        x = next;
126        if t.abs() <= 1e-15 * x && j > 0 {
127            break;
128        }
129    }
130    x
131}
132// ANCHOR_END: betaincinv
133
134#[cfg(test)]
135mod tests {
136    use super::*;
137
138    #[test]
139    fn gamma_inverse_round_trips() {
140        for a in [0.05, 0.3, 1.0, 2.5, 10.0, 150.0] {
141            for p in [1e-12, 1e-4, 0.1, 0.5, 0.9, 0.9999] {
142                let x = gammaincinv(a, p);
143                assert!((incomplete_gamma(a, x) - p).abs() <= 1e-12 * p.max(1e-300) + 1e-15, "a {a} p {p}: x {x}");
144                let x = gammainccinv(a, p);
145                assert!((incomplete_gamma_upper(a, x) - p).abs() <= 1e-12 * p, "upper a {a} q {p}: x {x}");
146            }
147        }
148    }
149
150    #[test]
151    fn beta_inverse_round_trips() {
152        for (a, b) in [(0.2, 0.3), (0.5, 0.5), (1.0, 3.0), (2.0, 5.0), (30.0, 0.7), (100.0, 200.0)] {
153            for p in [1e-10, 0.01, 0.3, 0.5, 0.8, 0.999] {
154                let x = betaincinv(a, b, p);
155                assert!((incomplete_beta(a, b, x) - p).abs() <= 1e-11 * p.max(1e-3), "a {a} b {b} p {p}: x {x}");
156            }
157        }
158    }
159}