Skip to main content

xsf/scipy_special/
ndtri_exp.rs

1//! Translated into pure Rust from `xsf/ndtri_exp.h` (scipy/xsf@acc2ec6). Original author:
2//! Albert Steppi.
3
4use core::f64::consts::{FRAC_1_SQRT_2, SQRT_2};
5
6use crate::utils::SQRT_FRAC_2_PI;
7use crate::xsf::cephes::ndtri::{NDTRI_P1, NDTRI_P2, NDTRI_Q1, NDTRI_Q2};
8use crate::xsf::cephes::polevl::{p1evl, polevl};
9
10/// Return inverse of log CDF of normal distribution for very small y
11///
12/// For p sufficiently small, the inverse of the CDF of the normal
13/// distribution can be approximated to high precision as a rational function
14/// in sqrt(-2.0 * log(p)).
15#[inline]
16fn ndtri_exp_small_y(y: f64) -> f64 {
17    // sqrt(-2 * y) is faster and has more precision but overflows when y < -DBL_MAX * 0.5
18    let x = if y >= -f64::MAX * 0.5 {
19        (-2.0 * y).sqrt()
20    } else {
21        SQRT_2 * (-y).sqrt()
22    };
23    let x0 = x - x.ln() / x;
24    let z = 1.0 / x;
25    let x1 = if x < 8.0 {
26        z * polevl(z, &NDTRI_P1) / p1evl(z, &NDTRI_Q1)
27    } else {
28        z * polevl(z, &NDTRI_P2) / p1evl(z, &NDTRI_Q2)
29    };
30    let r = x1 - x0;
31
32    // P2/Q2 are fitted for 8 <= x <= 64 and inaccurate up to x ~ 2^18, so refine with a Newton step
33    // (DLMF 3.8.4) on log_ndtr(r) = log(erfcx(t) / 2) - t^2, with t = -r/sqrt(2), whose derivative
34    // is sqrt(2/pi) / erfcx(t) (DLMF 7.2.2)
35    if x > 64.0 && x < 262_144.0 {
36        let t = -r * FRAC_1_SQRT_2;
37        let e = crate::erfcx(t);
38        r - ((e / 2.0).ln() - t * t - y) * e / SQRT_FRAC_2_PI
39    } else {
40        r
41    }
42}
43
44/// Inverse of [`log_ndtr`](crate::log_ndtr) vs x.
45///
46/// Allows for greater precision than [`ndtri`](crate::ndtri) composed with [`f64::exp`] for very
47/// small values of `y` and for `y` close to 0.
48///
49/// Corresponds to [`scipy.special.ndtri_exp`][scipy]
50///
51/// [scipy]: https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.ndtri_exp.html
52///
53/// # See also
54/// - [`log_ndtr`](crate::log_ndtr): log of the standard normal cumulative distribution function
55/// - [`ndtr`](crate::ndtr): standard normal cumulative distribution function
56/// - [`ndtri`](crate::ndtri): standard normal percentile function
57#[must_use]
58#[inline]
59pub fn ndtri_exp(y: f64) -> f64 {
60    if y < -f64::MAX {
61        f64::NEG_INFINITY
62    } else if y < -2.0 {
63        ndtri_exp_small_y(y)
64    } else if y > -0.145_413_457_868_859_06 {
65        // y > log1p(-exp(-2))
66        -crate::ndtri(-y.exp_m1())
67    } else {
68        crate::ndtri(y.exp())
69    }
70}