r2rs-nmath 0.1.1

Statistics programming for Rust based on R's nmath package
Documentation
// Translation of nmath's pcauchy
//
// 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 strafe_type::{FloatConstraint, LogProbability64, Natural64, Probability64, Real64};

use crate::traits::DPQ;

/// The distribution function of the Cauchy distribution.
pub fn pcauchy<R1: Into<Real64>, R2: Into<Real64>, N: Into<Natural64>>(
    x: R1,
    location: R2,
    scale: N,
    lower_tail: bool,
) -> Probability64 {
    pcauchy_inner(x, location, scale, lower_tail, false).into()
}

/// The distribution function of the Cauchy distribution.
pub fn log_pcauchy<R1: Into<Real64>, R2: Into<Real64>, N: Into<Natural64>>(
    x: R1,
    location: R2,
    scale: N,
    lower_tail: bool,
) -> LogProbability64 {
    pcauchy_inner(x, location, scale, lower_tail, true).into()
}

fn pcauchy_inner<R1: Into<Real64>, R2: Into<Real64>, N: Into<Natural64>>(
    x: R1,
    location: R2,
    scale: N,
    lower_tail: bool,
    log: bool,
) -> f64 {
    let mut x = x.into().unwrap();
    let location = location.into().unwrap();
    let scale = scale.into().unwrap();

    x = (x - location) / scale;
    if !x.is_finite() {
        return if x < 0.0 {
            f64::dt_0(lower_tail, log)
        } else {
            f64::dt_1(lower_tail, log)
        };
    }
    if !lower_tail {
        x = -x
    }
    /* for large x, the standard formula suffers from cancellation.
     * This is from Morten Welinder thanks to  Ian Smith's  (1/x).atan() : */
    if x.abs() > 1.0 {
        let y = (1.0 / x).atan() / std::f64::consts::PI;
        if x > 0.0 {
            y.d_clog(log)
        } else {
            (-y).d_val(log)
        }
    } else {
        (0.5 + x.atan() / std::f64::consts::PI).d_val(log)
    }
}