r2rs-nmath 0.1.1

Statistics programming for Rust based on R's nmath package
Documentation
// Translation of nmath's logspace functions (found in pgamma)
//
// 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 nonstdfloat::f128;
use num_traits::{Float, ToPrimitive};

/// Compute the log of a sum from logs of terms, i.e.,
///
/// log (exp (logx) + exp (logy))
///
/// without causing overflows and without throwing away large handfuls
/// of accuracy.
pub fn logspace_add(logx: f64, logy: f64) -> f64 {
    logx.max(logy) + (-(logx - logy).abs()).exp().ln_1p()
}

/// Compute the log of a difference from logs of terms, i.e.,
///
/// log (exp (logx) - exp (logy))
///
/// without causing overflows and without throwing away large handfuls
/// of accuracy.
pub fn logspace_sub(logx: f64, logy: f64) -> f64 {
    logx + (if logy - logx > -std::f64::consts::LN_2 {
        (-(logy - logx).exp_m1()).ln()
    } else {
        (-(logy - logx).exp()).ln_1p()
    })
}

/// Compute the log of a sum from logs of terms, i.e.,
///
/// $ log (sum_i  exp (logx\[i\]) ) = $
/// $ log (e^M * sum_i  e^(logx\[i\] - M) ) = $
/// $ M + log( sum_i  e^(logx\[i\] - M) $
///
/// without causing overflows or throwing much accuracy.
pub fn logspace_sum(logx: &[f64], n: usize) -> f64 {
    if n == 0 {
        return f64::NEG_INFINITY;
    } // =  sum(<empty>) .ln()
    if n == 1 {
        return logx[0];
    }
    if n == 2 {
        return logspace_add(logx[0], logx[1]);
    }
    // else (n >= 3) :
    let mut i = 0;
    // Mx := max_i x_i.ln()
    let mut Mx = logx[0];
    i = 1;
    while i < n {
        if Mx < logx[i] {
            Mx = logx[i]
        }
        i += 1
    }
    let mut s = f128::new(0.0);
    i = 0;
    while i < n {
        s += f128::new(logx[i] - Mx).exp();
        i += 1
    }
    return Mx + s.ln().to_f64().unwrap();
}