1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
//! Gamma function approximation
//!
//! This module calculates various gamma functions

use num_traits::Float;

mod f64;

/// Trait implementing the gamma functions
pub trait Gamma: Float {
    /// Calculates the logarithm of the Gamma function.
    fn ln_gamma(self) -> Self {
        self.gamma().ln()
    }
    /// Calculates the Gamma function.
    fn gamma(self) -> Self;
    /// Returns the upper incomplete regularized gamma function Q(a, x)
    fn upper_gamma_regularized(self, x: Self) -> Self {
        Self::one() - self.lower_gamma_regularized(x)
    }
    /// Returns the upper incomplete gamma function Q(a, x)
    fn upper_gamma_incomplete(self, x: Self) -> Self {
        self.upper_gamma_regularized(x) * self.gamma()
    }
    /// Returns the lower incomplete regularized gamma function P(a, x)
    fn lower_gamma_regularized(self, x: Self) -> Self;
    /// Returns the lower incomplete gamma function P(a, x)
    fn lower_gamma_incomplete(self, x: Self) -> Self {
        self.lower_gamma_regularized(x) * self.gamma()
    }
}

impl Gamma for f32 {
    fn gamma(self) -> Self {
        Gamma::gamma(self as f64) as f32
    }

    fn lower_gamma_regularized(self, x: Self) -> Self {
        Gamma::lower_gamma_regularized(self as f64, x as f64) as f32
    }

    fn ln_gamma(self) -> Self {
        Gamma::ln_gamma(self as f64) as f32
    }

    fn upper_gamma_regularized(self, x: Self) -> Self {
        Gamma::upper_gamma_regularized(self as f64, x as f64) as f32
    }

    fn upper_gamma_incomplete(self, x: Self) -> Self {
        Gamma::upper_gamma_incomplete(self as f64, x as f64) as f32
    }

    fn lower_gamma_incomplete(self, x: Self) -> Self {
        Gamma::lower_gamma_incomplete(self as f64, x as f64) as f32
    }
}

#[cfg(test)]
mod tests {
    use crate::gamma::Gamma;

    #[test]
    fn upper_gamma_accuracy() {
        assert!((Gamma::upper_gamma_regularized(1.5, 0.5) - 0.801252f64).abs() < 0.001);
    }
}