Skip to content

Commit

Permalink
Remove lazy-static and make FCACHE a proper const
Browse files Browse the repository at this point in the history
  • Loading branch information
anergictcell authored and YeungOnion committed Apr 22, 2024
1 parent 594bced commit d29d020
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 19 deletions.
1 change: 0 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@ rand = "0.8"
nalgebra = { version = "0.32", features = ["rand"] }
approx = "0.5.0"
num-traits = "0.2.14"
lazy_static = "1.4.0"

[dev-dependencies]
criterion = "0.3.3"
Expand Down
38 changes: 23 additions & 15 deletions src/function/factorial.rs
Original file line number Diff line number Diff line change
Expand Up @@ -90,26 +90,34 @@ pub fn checked_multinomial(n: u64, ni: &[u64]) -> Result<f64> {

// Initialization for pre-computed cache of 171 factorial
// values 0!...170!
lazy_static! {
static ref FCACHE: [f64; MAX_FACTORIAL + 1] = {
let mut fcache = [1.0; MAX_FACTORIAL + 1];
fcache
.iter_mut()
.enumerate()
.skip(1)
.fold(1.0, |acc, (i, elt)| {
let fac = acc * i as f64;
*elt = fac;
fac
});
fcache
};
}
const FCACHE: [f64; MAX_FACTORIAL + 1] = {
let mut fcache = [1.0; MAX_FACTORIAL + 1];

// `const` only allow while loops
let mut i = 1;
while i < MAX_FACTORIAL + 1 {
fcache[i] = fcache[i - 1] * i as f64;
i += 1;
}

fcache
};

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn test_fcache() {
assert!((FCACHE[0] - 1.0).abs() < f64::EPSILON);
assert!((FCACHE[1] - 1.0).abs() < f64::EPSILON);
assert!((FCACHE[2] - 2.0).abs() < f64::EPSILON);
assert!((FCACHE[3] - 6.0).abs() < f64::EPSILON);
assert!((FCACHE[4] - 24.0).abs() < f64::EPSILON);
assert!((FCACHE[70] - 1197857166996989e85).abs() < f64::EPSILON);
assert!((FCACHE[170] - 7257415615307994e291).abs() < f64::EPSILON);
}

#[test]
fn test_factorial_and_ln_factorial() {
let mut fac = 1.0;
Expand Down
3 changes: 0 additions & 3 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,9 +55,6 @@
#[macro_use]
extern crate approx;

#[macro_use]
extern crate lazy_static;

#[macro_export]
macro_rules! assert_almost_eq {
($a:expr, $b:expr, $prec:expr) => {
Expand Down

0 comments on commit d29d020

Please sign in to comment.