Skip to main content

lib_jsl_special_functions/
beta.rs

1//! Beta function.
2//!
3//! See the book entry [The gamma function and related functions](https://jwkunz.github.io/lib_jsl/book/special_functions/gamma.html#the-beta-function).
4
5use crate::gamma::{gamma, ln_gamma};
6
7/// The beta function B(a, b) = Γ(a)Γ(b)/Γ(a+b).
8///
9/// For positive arguments the result is accurate across the whole range (it switches to
10/// logarithms to avoid overflow). For other real arguments the gamma ratio is used directly.
11pub fn beta(a: f64, b: f64) -> f64 {
12    if a > 0.0 && b > 0.0 {
13        if a + b < 100.0 {
14            gamma(a) * gamma(b) / gamma(a + b)
15        } else {
16            ln_beta(a, b).exp()
17        }
18    } else {
19        gamma(a) * gamma(b) / gamma(a + b)
20    }
21}
22
23/// The natural logarithm of B(a, b) for positive `a` and `b`.
24pub fn ln_beta(a: f64, b: f64) -> f64 {
25    ln_gamma(a) + ln_gamma(b) - ln_gamma(a + b)
26}
27
28#[cfg(test)]
29mod tests {
30    use super::*;
31
32    #[test]
33    fn known_values() {
34        assert!((beta(2.0, 3.0) - 1.0 / 12.0).abs() < 1e-15);
35        assert!((beta(0.5, 0.5) - std::f64::consts::PI).abs() < 1e-14);
36        assert!((beta(1.0, 7.0) - 1.0 / 7.0).abs() < 1e-15);
37    }
38
39    #[test]
40    fn symmetric_and_large() {
41        assert!((beta(3.3, 8.1) - beta(8.1, 3.3)).abs() < 1e-18);
42        let v = beta(80.0, 90.0);
43        assert!((v.ln() - ln_beta(80.0, 90.0)).abs() < 1e-10);
44    }
45}