Random Number Generation
All functions that use random number generation must be provided with a random number generator (structs that implement the RNG
trait). Random number generators are accessible via the numerics
export. This allows applications to use multiple generators, to set and reuse seeds for their generators, and allows for multithreading without strange collisions.
By default in R
4.x the Mersenne Twister generator is used. Knowing this, and using the same seed for both R
and strafe we can generate the exact same numbers as shown below:
set.seed(1)
rnorm(5)
[1] -0.6264538 0.1836433 -0.8356286 1.5952808 0.3295078
use strafe::distribution::{Distribution, NormalBuilder}; use strafe::numerics::{MersenneTwister, RNG}; use strafe::types::FloatConstraint; fn main() { let mut rng = MersenneTwister::new(); rng.set_seed(1); let norm = NormalBuilder::new().build(); let rand_nums = (0..5) .map(|_| norm.random_sample(&mut rng).unwrap()) .collect::<Vec<_>>(); println!("{rand_nums:?}"); }
[-0.6264538, 0.1836433, -0.8356286, 1.5952808, 0.3295078]