r2rs-nmath 0.1.1

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

use crate::{distribution::chisq::rchisq, rng::NMathRNG, traits::RNG};

/// Pseudo-random variates from a t distribution.
///
/// This function calls rchisq and rnorm to do the real work.
pub fn rt<RA: Into<Rational64>, R: RNG>(df: RA, rng: &mut R) -> Real64 {
    let df = df.into().unwrap();

    return if !df.is_finite() {
        rng.norm_rand()
    } else {
        /* Some compilers (including MW6) evaluated this from right to left
        return norm_rand() / (rchisq(df) / df).sqrt(); */
        let num = rng.norm_rand();
        num / (rchisq(df, rng).unwrap() / df).sqrt()
    }
    .into();
}