Skip to main content

lib_jsl_special_functions/
gamma.rs

1//! Gamma function and related functions.
2//!
3//! See the book entry [The gamma function and related functions](https://jwkunz.github.io/lib_jsl/book/special_functions/gamma.html#the-gamma-function).
4
5use std::f64::consts::PI;
6
7const LANCZOS_G: f64 = 7.0;
8const LANCZOS_COEFFS: [f64; 9] = [
9    0.999_999_999_999_809_9,
10    676.520_368_121_885_1,
11    -1_259.139_216_722_402_8,
12    771.323_428_777_653_1,
13    -176.615_029_162_140_6,
14    12.507_343_278_686_905,
15    -0.138_571_095_265_720_12,
16    9.984_369_578_019_572e-6,
17    1.505_632_735_149_311_6e-7,
18];
19
20/// Sum of the Lanczos series for argument `x - 1` (i.e. already shifted).
21fn lanczos_sum(x: f64) -> f64 {
22    let mut a = LANCZOS_COEFFS[0];
23    for (i, &c) in LANCZOS_COEFFS.iter().enumerate().skip(1) {
24        a += c / (x + i as f64);
25    }
26    a
27}
28
29// ANCHOR: gamma
30/// The gamma function Γ(x) for real `x`.
31///
32/// Uses a Lanczos approximation (relative error about 1e-15) with the reflection formula for
33/// `x < 0.5`. Returns `NaN` at the poles (zero and the negative integers) and `+inf` on overflow
34/// (`x > 171.62`). Positive integers are evaluated exactly as `(x-1)!`.
35pub fn gamma(x: f64) -> f64 {
36    if x.is_nan() {
37        return f64::NAN;
38    }
39    if x == f64::INFINITY {
40        return f64::INFINITY;
41    }
42    if x <= 0.0 && x == x.floor() {
43        return f64::NAN;
44    }
45    if x == x.floor() && x <= 171.0 {
46        let mut r = 1.0;
47        let mut k = 2.0;
48        while k < x {
49            r *= k;
50            k += 1.0;
51        }
52        return r;
53    }
54    if x < 0.5 {
55        return PI / ((PI * x).sin() * gamma(1.0 - x));
56    }
57    if x > 171.7 {
58        return f64::INFINITY;
59    }
60    let x = x - 1.0;
61    let t = x + LANCZOS_G + 0.5;
62    // Split the power to avoid premature overflow of t^(x+0.5).
63    let half = t.powf(0.5 * (x + 0.5));
64    (2.0 * PI).sqrt() * half * (-t).exp() * half * lanczos_sum(x)
65}
66// ANCHOR_END: gamma
67
68/// The natural logarithm of |Γ(x)|. Returns `+inf` at the poles.
69pub fn ln_gamma(x: f64) -> f64 {
70    if x.is_nan() {
71        return f64::NAN;
72    }
73    if x <= 0.0 && x == x.floor() {
74        return f64::INFINITY;
75    }
76    if x == 1.0 || x == 2.0 {
77        return 0.0;
78    }
79    if x < 0.5 {
80        return (PI / (PI * x).sin().abs()).ln() - ln_gamma(1.0 - x);
81    }
82    let x = x - 1.0;
83    let t = x + LANCZOS_G + 0.5;
84    0.5 * (2.0 * PI).ln() + (x + 0.5) * t.ln() - t + lanczos_sum(x).ln()
85}
86
87/// The digamma function ψ(x) = Γ'(x)/Γ(x). Returns `NaN` at the poles.
88pub fn digamma(x: f64) -> f64 {
89    if x.is_nan() || (x <= 0.0 && x == x.floor()) {
90        return f64::NAN;
91    }
92    if x < 0.0 {
93        return digamma(1.0 - x) - PI / (PI * x).tan();
94    }
95    let mut x = x;
96    let mut acc = 0.0;
97    while x < 10.0 {
98        acc -= 1.0 / x;
99        x += 1.0;
100    }
101    let inv = 1.0 / x;
102    let inv2 = inv * inv;
103    // Asymptotic series with Bernoulli numbers.
104    let series = inv2
105        * (1.0 / 12.0
106            - inv2
107                * (1.0 / 120.0
108                    - inv2
109                        * (1.0 / 252.0
110                            - inv2 * (1.0 / 240.0 - inv2 * (1.0 / 132.0 - inv2 * 691.0 / 32760.0)))));
111    acc + x.ln() - 0.5 * inv - series
112}
113
114#[cfg(test)]
115mod tests {
116    use super::*;
117
118    fn close(a: f64, b: f64, rel: f64) -> bool {
119        (a - b).abs() <= rel * b.abs().max(1e-300)
120    }
121
122    #[test]
123    fn integers_and_half_integers() {
124        assert_eq!(gamma(1.0), 1.0);
125        assert_eq!(gamma(5.0), 24.0);
126        assert!(close(gamma(0.5), PI.sqrt(), 1e-14));
127        assert!(close(gamma(1.5), 0.5 * PI.sqrt(), 1e-14));
128        assert!(close(gamma(-0.5), -2.0 * PI.sqrt(), 1e-14));
129    }
130
131    #[test]
132    fn non_integer_values() {
133        assert!(close(gamma(0.1), 9.513507698668732, 1e-14));
134        assert!(close(gamma(3.7), 4.170651783796603, 1e-14));
135    }
136
137    #[test]
138    fn poles_and_overflow() {
139        assert!(gamma(0.0).is_nan());
140        assert!(gamma(-3.0).is_nan());
141        assert!(gamma(200.0).is_infinite());
142    }
143
144    #[test]
145    fn recurrence() {
146        for &x in &[0.3, 1.7, 5.2, 20.5, 60.1] {
147            assert!(close(gamma(x + 1.0), x * gamma(x), 1e-13));
148        }
149    }
150
151    #[test]
152    fn log_gamma() {
153        assert!(close(ln_gamma(0.5), 0.5 * PI.ln(), 1e-14));
154        assert!(close(ln_gamma(10.0), 12.801827480081469, 1e-14));
155        assert!(close(ln_gamma(1000.0), 5905.220423209181, 1e-14));
156        assert!(close(ln_gamma(-0.5), (2.0 * PI.sqrt()).ln(), 1e-14));
157    }
158
159    #[test]
160    fn digamma_values() {
161        let euler = 0.5772156649015329;
162        assert!(close(digamma(1.0), -euler, 1e-13));
163        assert!(close(digamma(0.5), -euler - 2.0 * 2f64.ln(), 1e-13));
164        assert!(close(digamma(10.0), 2.251752589066721, 1e-13));
165        assert!(close(digamma(-0.5), 0.03648997397857652, 1e-12));
166    }
167}