r2rs-nmath 0.1.1

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

use crate::{distribution::signrank::csignrank, traits::DPQ};

/// The distribution function of the Wilcoxon Signed Rank distribution.
pub fn psignrank<R: Into<Real64>, N: Into<Natural64>>(
    x: R,
    n: N,
    lower_tail: bool,
) -> Probability64 {
    psignrank_inner(x, n, lower_tail, false).into()
}

/// The distribution function of the Wilcoxon Signed Rank distribution.
pub fn log_psignrank<R: Into<Real64>, N: Into<Natural64>>(
    x: R,
    n: N,
    lower_tail: bool,
) -> LogProbability64 {
    psignrank_inner(x, n, lower_tail, true).into()
}

fn psignrank_inner<R: Into<Real64>, N: Into<Natural64>>(
    x: R,
    n: N,
    mut lower_tail: bool,
    log: bool,
) -> f64 {
    let mut x = x.into().unwrap();
    let mut n = n.into().unwrap();

    let mut i = 0;
    let mut f = 0.0;
    let mut p = 0.0;

    if !n.is_finite() {
        return f64::nan();
    }
    n = n.round();

    x = (x + 1e-7).round();
    if x < 0.0 {
        return f64::dt_0(lower_tail, log);
    }
    if x >= n * (n + 1.0) / 2.0 {
        return f64::dt_1(lower_tail, log);
    }

    let nn = n;
    f = (-n * std::f64::consts::LN_2).exp();
    p = 0.0;
    if x <= n * (n + 1.0) / 4.0 {
        i = 0;
        while i as f64 <= x {
            p += csignrank(i, nn as i32) * f;
            i += 1
        }
    } else {
        x = n * (n + 1.0) / 2.0 - x;
        i = 0;
        while (i as f64) < x {
            p += csignrank(i, nn as i32) * f;
            i += 1
        }
        lower_tail = !lower_tail
        /* p = 1 - p; */
    }

    return p.dt_val(lower_tail, log);
}