r2rs-nmath 0.1.1

Statistics programming for Rust based on R's nmath package
Documentation
// Translation of nmath's pgeom
//
// 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 distribution function of the geometric distribution.
pub fn pgeom<R: Into<Real64>, P: Into<Probability64>>(
    x: R,
    p: P,
    lower_tail: bool,
) -> Probability64 {
    pgeom_inner(x, p, lower_tail, false).into()
}

/// The distribution function of the geometric distribution.
pub fn log_pgeom<R: Into<Real64>, P: Into<Probability64>>(
    x: R,
    p: P,
    lower_tail: bool,
) -> LogProbability64 {
    pgeom_inner(x, p, lower_tail, true).into()
}

fn pgeom_inner<R: Into<Real64>, P: Into<Probability64>>(
    x: R,
    p: P,
    lower_tail: bool,
    log: bool,
) -> f64 {
    let mut x = x.into().unwrap();
    let p = p.into().unwrap();

    if p <= 0.0 {
        return f64::nan();
    }

    if x < 0.0 {
        return f64::dt_0(lower_tail, log);
    }
    if !x.is_finite() {
        return f64::dt_1(lower_tail, log);
    }
    x = (x + 1e-7).floor();

    if p == 1.0 {
        /* we cannot assume IEEE */
        x = if lower_tail { 1.0 } else { 0.0 };
        return if log { x.ln() } else { x };
    }
    x = (-p).ln_1p() * (x + 1.0);
    if log {
        x.dt_clog(lower_tail, true)
    } else if lower_tail {
        -x.exp_m1()
    } else {
        x.exp()
    }
}