r2rs-nmath 0.1.1

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

use crate::traits::DPQ;

/// The distribution function of the uniform distribution.
pub fn punif<R: Into<Real64>, F1: Into<Finite64>, F2: Into<Finite64>>(
    x: R,
    a: F1,
    b: F2,
    lower_tail: bool,
) -> Probability64 {
    punif_inner(x, a, b, lower_tail, false).into()
}

/// The distribution function of the uniform distribution.
pub fn log_punif<R: Into<Real64>, F1: Into<Finite64>, F2: Into<Finite64>>(
    x: R,
    a: F1,
    b: F2,
    lower_tail: bool,
) -> LogProbability64 {
    punif_inner(x, a, b, lower_tail, true).into()
}

fn punif_inner<R: Into<Real64>, F1: Into<Finite64>, F2: Into<Finite64>>(
    x: R,
    a: F1,
    b: F2,
    lower_tail: bool,
    log: bool,
) -> f64 {
    let x = x.into().unwrap();
    let a = a.into().unwrap();
    let b = b.into().unwrap();

    if b < a {
        return f64::nan();
    }

    if x >= b {
        return f64::dt_1(lower_tail, log);
    }
    if x <= a {
        return f64::dt_0(lower_tail, log);
    }
    return if lower_tail {
        ((x - a) / (b - a)).d_val(log)
    } else {
        ((b - x) / (b - a)).d_val(log)
    };
}