r2rs-nmath 0.1.1

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

use crate::traits::DPQ;

/// The density of the lognormal distribution.
pub fn dlnorm<R1: Into<Real64>, R2: Into<Real64>, P: Into<Positive64>>(
    x: R1,
    meanlog: R2,
    sdlog: P,
    log: bool,
) -> Real64 {
    let x = x.into().unwrap();
    let meanlog = meanlog.into().unwrap();
    let sdlog = sdlog.into().unwrap();

    let mut y = 0.0;

    if !x.is_finite() && x.ln() == meanlog {
        /* log(x) - meanlog is NaN */
        return f64::nan().into();
    }
    if sdlog == 0.0 {
        return if x.ln() == meanlog {
            f64::infinity()
        } else {
            f64::d_0(log)
        }
        .into();
    }
    if x <= 0.0 {
        return f64::d_0(log).into();
    }

    y = (x.ln() - meanlog) / sdlog;
    if log {
        -(strafe_consts::LN_SQRT_2TPI + 0.5 * y * y + (x * sdlog).ln())
    } else {
        (strafe_consts::_1DSQRT_2TPI * (-0.5 * y * y).exp()) / (x * sdlog)
    }
    .into()
    /* M_1_SQRT_2PI = 1 / sqrt(2 * pi) */
}