use std::f64::consts::SQRT_2;
use thiserror::Error;
#[derive(Debug, Clone, PartialEq, Error)]
pub enum MathError {
#[error("Probability {0} is out of domain (0, 1)")]
ProbabilityOutOfRange(f64),
}
const INV_SQRT_2PI: f64 = 0.398_942_280_401_432_7;
#[inline]
pub fn normal_pdf(x: f64) -> f64 {
INV_SQRT_2PI * (-0.5 * x * x).exp()
}
#[inline]
pub fn normal_cdf(x: f64) -> f64 {
0.5 * (1.0 + statrs::function::erf::erf(x / SQRT_2))
}
pub fn inverse_normal_cdf(p: f64) -> Result<f64, MathError> {
if p <= 0.0 || p >= 1.0 {
return Err(MathError::ProbabilityOutOfRange(p));
}
const A1: f64 = -3.969_683_028_665_376e+01;
const A2: f64 = 2.209_460_984_245_205e+02;
const A3: f64 = -2.759_285_104_469_687e+02;
const A4: f64 = 1.383_577_518_672_690e+02;
const A5: f64 = -3.066_479_806_614_716e+01;
const A6: f64 = 2.506_628_277_459_239e+00;
const B1: f64 = -5.447_609_879_822_406e+01;
const B2: f64 = 1.615_858_368_580_409e+02;
const B3: f64 = -1.556_989_798_598_866e+02;
const B4: f64 = 6.680_131_188_771_972e+01;
const B5: f64 = -1.328_068_155_288_572e+01;
const C1: f64 = -7.784_894_002_430_293e-03;
const C2: f64 = -3.223_964_580_411_365e-01;
const C3: f64 = -2.400_758_277_161_838e+00;
const C4: f64 = -2.549_732_539_343_734e+00;
const C5: f64 = 4.374_664_141_464_968e+00;
const C6: f64 = 2.938_163_982_698_783e+00;
const D1: f64 = 7.784_695_709_041_462e-03;
const D2: f64 = 3.224_671_290_700_398e-01;
const D3: f64 = 2.445_134_137_142_996e+00;
const D4: f64 = 3.754_408_661_907_416e+00;
const P_LOW: f64 = 0.02425;
const P_HIGH: f64 = 1.0 - P_LOW;
let x = if p < P_LOW {
let q = (-2.0 * p.ln()).sqrt();
(((((C1 * q + C2) * q + C3) * q + C4) * q + C5) * q + C6)
/ ((((D1 * q + D2) * q + D3) * q + D4) * q + 1.0)
} else if p <= P_HIGH {
let q = p - 0.5;
let r = q * q;
(((((A1 * r + A2) * r + A3) * r + A4) * r + A5) * r + A6) * q
/ (((((B1 * r + B2) * r + B3) * r + B4) * r + B5) * r + 1.0)
} else {
let q = (-2.0 * (1.0 - p).ln()).sqrt();
-(((((C1 * q + C2) * q + C3) * q + C4) * q + C5) * q + C6)
/ ((((D1 * q + D2) * q + D3) * q + D4) * q + 1.0)
};
let err = normal_cdf(x) - p;
let pdf = normal_pdf(x);
let x_refined = x - err / (pdf + x * err * 0.5);
Ok(x_refined)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_normal_symmetry() {
for z in [0.0, 0.5, 1.0, 1.96, 2.58, 3.0] {
assert!((normal_pdf(z) - normal_pdf(-z)).abs() < 1e-15);
assert!((normal_cdf(z) + normal_cdf(-z) - 1.0).abs() < 1e-15);
}
}
#[test]
fn test_roundtrip_cdf_inverse() {
for p in [
0.0001, 0.01, 0.05, 0.1, 0.25, 0.5, 0.75, 0.9, 0.95, 0.99, 0.9999,
] {
let z = inverse_normal_cdf(p).unwrap();
let p_rec = normal_cdf(z);
assert!(
(p - p_rec).abs() < 1e-12,
"Failed at p={}: got {}",
p,
p_rec
);
}
}
}