lib_jsl_special_functions/
incomplete_gamma.rs1use 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
14fn 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
30fn 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}
57pub 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
79pub 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 let x = 2.5f64;
114 assert!((incomplete_gamma(2.0, x) - (1.0 - (1.0 + x) * (-x).exp())).abs() < 1e-14);
115 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 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}