Skip to main content

xsf/scipy_special/
log_gammainc.rs

1//! The edge cases follow `lgamma_p_wrap` and `lgamma_q_wrap` in
2//! `scipy/special/boost_special_functions.h`. Unlike SciPy, which uses Boost's `lgamma_p` and
3//! `lgamma_q`, these use the Cephes `igam` and `igamc`, with the same split as Boost: the log of
4//! the complement where it is small, and a log-space series where the function underflows.
5
6use crate::xsf::cephes::{igam, igam_exp_scaled, igamc, igamc_exp_scaled};
7
8/// Log of the regularized lower incomplete gamma function, $\ln P(a,x)$
9///
10/// Accurate also where $P(a,x)$ underflows, or is close to 1.
11///
12/// Corresponds to [`scipy.special.log_gammainc`][scipy].
13///
14/// [scipy]: https://scipy.github.io/devdocs/reference/generated/scipy.special.log_gammainc.html
15///
16/// # See also
17/// - [`gammainc`](crate::gammainc): Regularized lower incomplete gamma function, $P(a,x)$
18/// - [`log_gammaincc`]: Log of the regularized upper incomplete gamma function, $\ln Q(a,x)$
19#[must_use]
20#[inline]
21pub fn log_gammainc(a: f64, x: f64) -> f64 {
22    ln_igam(a, x, igam, igamc, igam_exp_scaled)
23}
24
25/// Log of the regularized upper incomplete gamma function, $\ln Q(a,x)$
26///
27/// Accurate also where $Q(a,x)$ underflows, or is close to 1.
28///
29/// Corresponds to [`scipy.special.log_gammaincc`][scipy].
30///
31/// [scipy]: https://scipy.github.io/devdocs/reference/generated/scipy.special.log_gammaincc.html
32///
33/// # See also
34/// - [`gammaincc`](crate::gammaincc): Regularized upper incomplete gamma function, $Q(a,x)$
35/// - [`log_gammainc`]: Log of the regularized lower incomplete gamma function, $\ln P(a,x)$
36#[must_use]
37#[inline]
38pub fn log_gammaincc(a: f64, x: f64) -> f64 {
39    ln_igam(a, x, igamc, igam, |a, x| Some(igamc_exp_scaled(a, x)))
40}
41
42/// `ln(f(a, x))`, with `f` either `igam` or `igamc`, `complement` the other one, and `exp_scaled`
43/// as `igam_exp_scaled` for `f`
44fn ln_igam(
45    a: f64,
46    x: f64,
47    f: fn(f64, f64) -> f64,
48    complement: fn(f64, f64) -> f64,
49    exp_scaled: fn(f64, f64) -> Option<(f64, f64)>,
50) -> f64 {
51    // unlike `igam` and `igamc`, NaN for `a = 0`
52    if !(a > 0.0) {
53        return f64::NAN;
54    }
55    let v = f(a, x);
56    // exact for `x = 0`, `x = inf` or `a = inf`, and NaN for `x < 0`
57    if !(x > 0.0) || x.is_infinite() || a.is_infinite() {
58        return v.ln();
59    }
60    // `ln(v)` loses `~eps / (1 - v)` relative to the complement
61    if v > 0.5 {
62        return (-complement(a, x)).ln_1p();
63    }
64    if v >= f64::MIN_POSITIVE {
65        return v.ln();
66    }
67    exp_scaled(a, x).map_or(v.ln(), |(m, ln_f)| m.ln() + ln_f)
68}