r2rs-nmath 0.1.1

Statistics programming for Rust based on R's nmath package
Documentation
// Translation of nmath's qlogis
//
// 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, Probability64, Rational64, Real64};

use crate::traits::DPQ;

pub fn qlogis<P: Into<Probability64>, RE: Into<Real64>, RA: Into<Rational64>>(
    p: P,
    location: RE,
    scale: RA,
    lower_tail: bool,
) -> Real64 {
    let p = p.into().unwrap();
    qlogis_inner(p, location, scale, lower_tail, false)
}

pub fn log_qlogis<LP: Into<LogProbability64>, RE: Into<Real64>, RA: Into<Rational64>>(
    p: LP,
    location: RE,
    scale: RA,
    lower_tail: bool,
) -> Real64 {
    let p = p.into().unwrap();
    qlogis_inner(p, location, scale, lower_tail, true)
}

pub fn qlogis_inner<RE: Into<Real64>, RA: Into<Rational64>>(
    mut p: f64,
    location: RE,
    scale: RA,
    lower_tail: bool,
    log: bool,
) -> Real64 {
    let location = location.into().unwrap();
    let scale = scale.into().unwrap();

    if let Some(ret) = p.q_p01_boundaries(f64::NEG_INFINITY, f64::infinity(), lower_tail, log) {
        return ret.into();
    }

    if scale == 0.0 {
        return location.into();
    }

    p = if log {
        /* p := logit(p) = ( p / (1-p) ).ln()  : */
        if lower_tail {
            p - p.log1_exp()
        } else {
            p.log1_exp() - p
        }
    } else if lower_tail {
        p / (1.0 - p).ln()
    } else {
        ((1.0 - p) / p).ln()
    };
    (location + scale * p).into()
}