r2rs-nmath 0.1.1

Statistics programming for Rust based on R's nmath package
Documentation
// Translation of nmath's pnf
//
// Copyright (C) 2020 neek-sss
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

use num_traits::Float;
use strafe_type::{
    FloatConstraint, LogProbability64, Positive64, Probability64, Rational64, Real64,
};

use crate::{
    distribution::{
        beta::pnbeta2,
        chisq::{log_pnchisq, pnchisq},
    },
    traits::DPQ,
};

/// The distribution function of the non-central F distribution.
pub fn pnf<RE: Into<Real64>, RA1: Into<Rational64>, RA2: Into<Rational64>, P: Into<Positive64>>(
    x: RE,
    df1: RA1,
    df2: RA2,
    ncp: P,
    lower_tail: bool,
) -> Probability64 {
    pnf_inner(x, df1, df2, ncp, lower_tail, false).into()
}

/// The distribution function of the non-central F distribution.
pub fn log_pnf<
    RE: Into<Real64>,
    RA1: Into<Rational64>,
    RA2: Into<Rational64>,
    P: Into<Positive64>,
>(
    x: RE,
    df1: RA1,
    df2: RA2,
    ncp: P,
    lower_tail: bool,
) -> LogProbability64 {
    pnf_inner(x, df1, df2, ncp, lower_tail, true).into()
}

fn pnf_inner<
    RE: Into<Real64>,
    RA1: Into<Rational64>,
    RA2: Into<Rational64>,
    P: Into<Positive64>,
>(
    x: RE,
    df1: RA1,
    df2: RA2,
    ncp: P,
    lower_tail: bool,
    log: bool,
) -> f64 {
    let x = x.into().unwrap();
    let df1 = df1.into().unwrap();
    let df2 = df2.into().unwrap();
    let ncp = ncp.into().unwrap();

    let mut y = 0.0;
    if !ncp.is_finite() {
        return f64::nan();
    }
    if !df1.is_finite() && !df2.is_finite() {
        /* both +Inf */
        return f64::nan();
    }

    if let Some(ret) = x.p_bounds_01(0.0, f64::infinity(), lower_tail, log) {
        return ret;
    }

    if df2 > 1e8 {
        /* avoid problems with +Inf and loss of accuracy */
        return if log {
            log_pnchisq(x * df1, df1, ncp, lower_tail).unwrap()
        } else {
            pnchisq(x * df1, df1, ncp, lower_tail).unwrap()
        };
    }

    y = df1 / df2 * x;
    pnbeta2(
        y / (1.0 + y),
        1.0 / (1.0 + y),
        df1 / 2.0,
        df2 / 2.0,
        ncp,
        lower_tail,
        log,
    )
}