Skip to main content

lib_jsl_special_functions/
incomplete_gamma.rs

1//! Incomplete gamma function.
2//!
3//! See the book entry [Incomplete gamma and beta functions and the error function](https://jwkunz.github.io/lib_jsl/book/special_functions/incomplete.html#the-incomplete-gamma-function).
4
5use crate::gamma::ln_gamma;
6
7const EPS: f64 = 1e-16;
8const FPMIN: f64 = f64::MIN_POSITIVE / EPS;
9
10fn max_iter(a: f64) -> usize {
11    1000 + (20.0 * a.sqrt()) as usize
12}
13
14/// Series for the regularized lower function P(a, x); best for `x < a + 1`.
15fn series(a: f64, x: f64) -> f64 {
16    let mut ap = a;
17    let mut del = 1.0 / a;
18    let mut sum = del;
19    for _ in 0..max_iter(a) {
20        ap += 1.0;
21        del *= x / ap;
22        sum += del;
23        if del.abs() < sum.abs() * EPS {
24            break;
25        }
26    }
27    sum * (-x + a * x.ln() - ln_gamma(a)).exp()
28}
29
30// ANCHOR: gamma_cf
31/// Continued fraction (modified Lentz) for the regularized upper function Q(a, x); `x >= a + 1`.
32fn continued_fraction(a: f64, x: f64) -> f64 {
33    let mut b = x + 1.0 - a;
34    let mut c = 1.0 / FPMIN;
35    let mut d = 1.0 / b;
36    let mut h = d;
37    for i in 1..max_iter(a) {
38        let an = -(i as f64) * (i as f64 - a);
39        b += 2.0;
40        d = an * d + b;
41        if d.abs() < FPMIN {
42            d = FPMIN;
43        }
44        c = b + an / c;
45        if c.abs() < FPMIN {
46            c = FPMIN;
47        }
48        d = 1.0 / d;
49        let del = d * c;
50        h *= del;
51        if (del - 1.0).abs() < EPS {
52            break;
53        }
54    }
55    (-x + a * x.ln() - ln_gamma(a)).exp() * h
56}
57// ANCHOR_END: gamma_cf
58
59/// The regularized lower incomplete gamma function P(a, x) = γ(a, x) / Γ(a), for `a > 0`, `x >= 0`.
60///
61/// Returns `NaN` for invalid arguments.
62pub fn incomplete_gamma(a: f64, x: f64) -> f64 {
63    if !(a > 0.0) || x.is_nan() || x < 0.0 {
64        return f64::NAN;
65    }
66    if x == 0.0 {
67        return 0.0;
68    }
69    if x.is_infinite() {
70        return 1.0;
71    }
72    if x < a + 1.0 {
73        series(a, x)
74    } else {
75        1.0 - continued_fraction(a, x)
76    }
77}
78
79/// The regularized upper incomplete gamma function Q(a, x) = 1 - P(a, x), computed without
80/// cancellation in the tail.
81pub fn incomplete_gamma_upper(a: f64, x: f64) -> f64 {
82    if !(a > 0.0) || x.is_nan() || x < 0.0 {
83        return f64::NAN;
84    }
85    if x == 0.0 {
86        return 1.0;
87    }
88    if x.is_infinite() {
89        return 0.0;
90    }
91    if x < a + 1.0 {
92        1.0 - series(a, x)
93    } else {
94        continued_fraction(a, x)
95    }
96}
97
98#[cfg(test)]
99mod tests {
100    use super::*;
101
102    #[test]
103    fn a_equals_one_is_exponential() {
104        for &x in &[0.1, 0.5, 1.0, 3.0, 10.0] {
105            assert!((incomplete_gamma(1.0, x) - (1.0 - (-x).exp())).abs() < 1e-14);
106            assert!((incomplete_gamma_upper(1.0, x) - (-x).exp()).abs() < 1e-14);
107        }
108    }
109
110    #[test]
111    fn known_values() {
112        // P(2, x) = 1 - (1 + x) e^-x
113        let x = 2.5f64;
114        assert!((incomplete_gamma(2.0, x) - (1.0 - (1.0 + x) * (-x).exp())).abs() < 1e-14);
115        // P(0.5, 1) = erf(1)
116        assert!((incomplete_gamma(0.5, 1.0) - 0.8427007929497149).abs() < 1e-14);
117        assert!((incomplete_gamma(5.0, 5.0) - 0.5595067149347875).abs() < 1e-13);
118    }
119
120    #[test]
121    fn complementarity_and_tails() {
122        for &(a, x) in &[(0.3, 0.2), (4.0, 9.0), (50.0, 40.0), (50.0, 70.0)] {
123            assert!((incomplete_gamma(a, x) + incomplete_gamma_upper(a, x) - 1.0).abs() < 1e-13);
124        }
125        // Deep upper tail keeps relative accuracy: Q(1, 50) = e^-50.
126        assert!((incomplete_gamma_upper(1.0, 50.0) / (-50.0f64).exp() - 1.0).abs() < 1e-12);
127    }
128
129    #[test]
130    fn invalid() {
131        assert!(incomplete_gamma(-1.0, 1.0).is_nan());
132        assert!(incomplete_gamma(1.0, -1.0).is_nan());
133        assert_eq!(incomplete_gamma(2.0, 0.0), 0.0);
134    }
135}