r2rs-nmath 0.1.1

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

use super::{log_ppois, ppois};
use crate::{distribution::func::discrete_body, traits::DPQ};

/// The quantile function of the Poisson distribution.
///
/// Uses the Cornish-Fisher Expansion to include a skewness
/// correction to a normal approximation.  This gives an
/// initial value which never seems to be off by more than
/// 1 or 2.  A search is then conducted of values close to
/// this initial start point.
pub fn qpois<PR: Into<Probability64>, PO: Into<Positive64>>(
    p: PR,
    lambda: PO,
    lower_tail: bool,
) -> Real64 {
    let p = p.into().unwrap();
    qpois_inner(p, lambda, lower_tail, false)
}

/// The quantile function of the Poisson distribution.
///
/// Uses the Cornish-Fisher Expansion to include a skewness
/// correction to a normal approximation.  This gives an
/// initial value which never seems to be off by more than
/// 1 or 2.  A search is then conducted of values close to
/// this initial start point.
pub fn log_qpois<LP: Into<LogProbability64>, P: Into<Positive64>>(
    p: LP,
    lambda: P,
    lower_tail: bool,
) -> Real64 {
    let p = p.into().unwrap();
    qpois_inner(p, lambda, lower_tail, true)
}

fn qpois_inner<P: Into<Positive64>>(p: f64, lambda: P, lower_tail: bool, log: bool) -> Real64 {
    let lambda = lambda.into().unwrap();

    if !lambda.is_finite() {
        return f64::nan().into();
    }
    if lambda == 0.0 {
        return 0.0.into();
    }
    if p == f64::dt_0(lower_tail, log) {
        return 0.0.into();
    }
    if p == f64::dt_1(lower_tail, log) {
        return f64::infinity().into();
    }

    let mu = lambda;
    let sigma = lambda.sqrt();
    // had gamma = sigma; PR#8058 should be kurtosis which is mu^-0.5 = 1/sigma
    let gamma = 1.0 / sigma;

    let ret = discrete_body(
        mu,
        sigma,
        gamma,
        p,
        None,
        lower_tail,
        log,
        &|p| ppois(p, lambda, lower_tail).into(),
        &|p| log_ppois(p, lambda, lower_tail).into(),
    );
    ret.into()
}