quantlib_rs 0.1.0

A ground-up, idiomatic Rust quantitative finance library inspired by QuantLib.
Documentation
//! Standard Normal distribution PDF, CDF, and Peter Acklam Inverse CDF.

use std::f64::consts::SQRT_2;
use thiserror::Error;

/// Math and distribution errors.
#[derive(Debug, Clone, PartialEq, Error)]
pub enum MathError {
    /// Probability argument out of bounds for inverse CDF.
    #[error("Probability {0} is out of domain (0, 1)")]
    ProbabilityOutOfRange(f64),
}

const INV_SQRT_2PI: f64 = 0.398_942_280_401_432_7; // 1 / sqrt(2 * pi)

/// Standard normal probability density function (PDF):
/// $$\phi(x) = \frac{1}{\sqrt{2\pi}} e^{-x^2 / 2}$$
///
/// # Examples
/// ```
/// use quantlib_rs::math::distributions::normal_pdf;
///
/// assert!((normal_pdf(0.0) - 0.3989422804014327).abs() < 1e-12);
/// ```
#[inline]
pub fn normal_pdf(x: f64) -> f64 {
    INV_SQRT_2PI * (-0.5 * x * x).exp()
}

/// Standard normal cumulative distribution function (CDF):
/// $$\Phi(x) = \frac{1}{2}\left[1 + \text{erf}\left(\frac{x}{\sqrt{2}}\right)\right]$$
///
/// Computed via the error function in `statrs`.
///
/// # Examples
/// ```
/// use quantlib_rs::math::distributions::normal_cdf;
///
/// assert!((normal_cdf(0.0) - 0.5).abs() < 1e-12);
/// assert!((normal_cdf(1.959963984540) - 0.975).abs() < 1e-5);
/// ```
#[inline]
pub fn normal_cdf(x: f64) -> f64 {
    0.5 * (1.0 + statrs::function::erf::erf(x / SQRT_2))
}

/// Inverse of the standard normal cumulative distribution function ($\Phi^{-1}(p)$).
///
/// Implemented using Peter Acklam's rational approximation with a Halley refinement step,
/// achieving double precision accuracy ($\approx 10^{-16}$) across $(0, 1)$.
///
/// # Examples
/// ```
/// use quantlib_rs::math::distributions::inverse_normal_cdf;
///
/// let z = inverse_normal_cdf(0.975).unwrap();
/// assert!((z - 1.959963984540054).abs() < 1e-10);
/// assert!((inverse_normal_cdf(0.5).unwrap()).abs() < 1e-15);
/// ```
pub fn inverse_normal_cdf(p: f64) -> Result<f64, MathError> {
    if p <= 0.0 || p >= 1.0 {
        return Err(MathError::ProbabilityOutOfRange(p));
    }

    // Coefficients for Acklam's algorithm
    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 {
        // Lower tail
        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 {
        // Central region
        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 {
        // Upper tail
        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)
    };

    // Halley refinement step for full double precision
    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
            );
        }
    }
}