Skip to main content

lib_jsl_special_functions/
polygamma.rs

1//! Polygamma functions, the multivariate log-gamma function, and Bernoulli and Euler numbers
2//! (SciPy's `polygamma`, `multigammaln`, `bernoulli`, `euler`).
3//!
4//! See the book entry [Log-domain functions and inverse incomplete integrals](https://jwkunz.github.io/lib_jsl/book/special_functions/log-domain.html#polygamma-and-friends).
5
6use crate::factorial::factorial_f64;
7use crate::gamma::{digamma, ln_gamma};
8use crate::zeta::{hurwitz_zeta, zeta};
9use std::f64::consts::PI;
10
11// ANCHOR: polygamma
12/// The polygamma function `ψ⁽ⁿ⁾(x)`, the `n`-th derivative of the digamma function (SciPy's
13/// `polygamma`). For `n ≥ 1`, `ψ⁽ⁿ⁾(x) = (−1)ⁿ⁺¹ n! ζ(n + 1, x)` with the Hurwitz zeta function;
14/// negative non-integer `x` is first shifted to positive values by
15/// `ψ⁽ⁿ⁾(x) = ψ⁽ⁿ⁾(x + 1) + (−1)ⁿ⁺¹ n! / xⁿ⁺¹`. `NaN` at the poles `x = 0, −1, −2, …`.
16pub fn polygamma(n: u32, x: f64) -> f64 {
17    if n == 0 {
18        return digamma(x);
19    }
20    if x.is_nan() || (x <= 0.0 && x == x.floor()) {
21        return f64::NAN;
22    }
23    let sign = if n % 2 == 1 { 1.0 } else { -1.0 };
24    let nf = factorial_f64(n as u64);
25    let (mut x, mut shift) = (x, 0.0);
26    while x <= 0.0 {
27        shift += sign * nf / x.powi(n as i32 + 1);
28        x += 1.0;
29    }
30    sign * nf * hurwitz_zeta(n as f64 + 1.0, x) + shift
31}
32// ANCHOR_END: polygamma
33
34/// The logarithm of the multivariate gamma function,
35/// `ln Γ_d(a) = d(d−1)/4 · ln π + Σ_{j=1}^{d} ln Γ(a + (1 − j)/2)`, for `a > (d − 1)/2`
36/// (SciPy's `multigammaln`; it normalises the Wishart density).
37pub fn multigammaln(a: f64, d: u32) -> f64 {
38    if !(a > (d as f64 - 1.0) / 2.0) {
39        return f64::NAN;
40    }
41    let d = d as f64;
42    d * (d - 1.0) / 4.0 * PI.ln() + (1..=d as u32).map(|j| ln_gamma(a + (1.0 - j as f64) / 2.0)).sum::<f64>()
43}
44
45/// The Bernoulli numbers `B₀, …, B_n` with `B₁ = −1/2` (SciPy's `bernoulli`). The odd ones
46/// beyond `B₁` are zero; the even ones come from `B_{2k} = (−1)^{k+1} 2 (2k)! ζ(2k) / (2π)^{2k}`,
47/// accurate to rounding up to `n ≈ 260`, where they overflow.
48pub fn bernoulli(n: usize) -> Vec<f64> {
49    let mut b = vec![0.0; n + 1];
50    b[0] = 1.0;
51    if n >= 1 {
52        b[1] = -0.5;
53    }
54    let mut ratio = 1.0; // (2k)! / (2π)^{2k}, updated incrementally.
55    for k in 1..=n / 2 {
56        let m = 2 * k;
57        ratio *= ((m - 1) * m) as f64 / (2.0 * PI).powi(2);
58        b[m] = if k % 2 == 1 { 2.0 } else { -2.0 } * ratio * zeta(m as f64);
59    }
60    b
61}
62
63/// The Euler numbers `E₀, …, E_n` (SciPy's `euler`): the coefficients of `sech t = Σ E_n tⁿ/n!`,
64/// zero for odd `n`, from `E_{2k} = (−1)^k 2 (2k)! (2/π)^{2k+1} β(2k + 1)` with Dirichlet's
65/// `β(s) = Σ (−1)^j/(2j + 1)^s = 4^{−s} (ζ(s, 1/4) − ζ(s, 3/4))`.
66pub fn euler(n: usize) -> Vec<f64> {
67    let mut e = vec![0.0; n + 1];
68    e[0] = 1.0;
69    let mut ratio = 2.0 / PI; // (2k)! (2/π)^{2k+1}
70    for k in 1..=n / 2 {
71        let m = 2 * k;
72        ratio *= ((m - 1) * m) as f64 * (2.0 / PI).powi(2);
73        let s = m as f64 + 1.0;
74        let beta = 4f64.powf(-s) * (hurwitz_zeta(s, 0.25) - hurwitz_zeta(s, 0.75));
75        e[m] = if k % 2 == 1 { -2.0 } else { 2.0 } * ratio * beta;
76    }
77    e
78}
79
80#[cfg(test)]
81mod tests {
82    use super::*;
83
84    #[test]
85    fn polygamma_values() {
86        // ψ'(1) = π²/6, ψ''(1) = −2ζ(3), ψ'(1/2) = π²/2.
87        assert!((polygamma(1, 1.0) - PI * PI / 6.0).abs() < 1e-14);
88        assert!((polygamma(2, 1.0) + 2.0 * 1.2020569031595942).abs() < 1e-13);
89        assert!((polygamma(1, 0.5) - PI * PI / 2.0).abs() < 1e-13);
90        // Recurrence across the poles: ψ'(x) = ψ'(x + 1) + 1/x².
91        let x = -2.3;
92        assert!((polygamma(1, x) - polygamma(1, x + 1.0) - 1.0 / (x * x)).abs() < 1e-10);
93        assert!(polygamma(1, -2.0).is_nan());
94    }
95
96    #[test]
97    fn bernoulli_and_euler_numbers() {
98        let b = bernoulli(12);
99        let want = [1.0, -0.5, 1.0 / 6.0, 0.0, -1.0 / 30.0, 0.0, 1.0 / 42.0, 0.0, -1.0 / 30.0, 0.0, 5.0 / 66.0, 0.0, -691.0 / 2730.0];
100        for (g, w) in b.iter().zip(want) {
101            assert!((g - w).abs() < 1e-15 * w.abs().max(1.0), "{g} vs {w}");
102        }
103        let e = euler(10);
104        let want = [1.0, 0.0, -1.0, 0.0, 5.0, 0.0, -61.0, 0.0, 1385.0, 0.0, -50521.0];
105        for (g, w) in e.iter().zip(want) {
106            assert!((g - w).abs() < 1e-12 * w.abs().max(1.0), "{g} vs {w}");
107        }
108    }
109
110    #[test]
111    fn multigammaln_reduces_to_ln_gamma() {
112        assert!((multigammaln(3.5, 1) - ln_gamma(3.5)).abs() < 1e-14);
113        // d = 2: ln π / 2 + ln Γ(a) + ln Γ(a − 1/2).
114        assert!((multigammaln(2.0, 2) - (0.5 * PI.ln() + ln_gamma(2.0) + ln_gamma(1.5))).abs() < 1e-14);
115    }
116}