r2rs-nmath 0.1.1

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

use crate::traits::DPQ;

/// The quantile function of the geometric distribution.
pub fn qgeom<P1: Into<Probability64>, P2: Into<Probability64>>(
    p: P1,
    prob: P2,
    lower_tail: bool,
) -> Real64 {
    let p = p.into().unwrap();
    qgeom_inner(p, prob, lower_tail, false)
}

/// The quantile function of the geometric distribution.
pub fn log_qgeom<LP: Into<LogProbability64>, P: Into<Probability64>>(
    p: LP,
    prob: P,
    lower_tail: bool,
) -> Real64 {
    let p = p.into().unwrap();
    qgeom_inner(p, prob, lower_tail, true)
}

pub fn qgeom_inner<P: Into<Probability64>>(p: f64, prob: P, lower_tail: bool, log: bool) -> Real64 {
    let prob = prob.into().unwrap();

    if prob <= 0.0 {
        return f64::nan().into();
    }

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

    /* add a fuzz to ensure left continuity, but value must be >= 0 */
    (p.dt_clog(lower_tail, log) / (-prob).ln_1p() - 1.0 - 1e-12)
        .ceil()
        .max(0.0)
        .into()
}