pub fn mix_seed(seed: u64, id: u64) -> u64 {
let mut z = seed ^ id.wrapping_mul(0x9E37_79B9_7F4A_7C15);
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
z ^ (z >> 31)
}
#[derive(Clone, Debug)]
pub struct Rng {
state: u64,
}
impl Rng {
pub fn new(seed: u64) -> Self {
Rng { state: seed }
}
pub fn split(seed: u64, id: u64) -> Self {
Rng::new(mix_seed(seed, id))
}
#[inline]
fn next_u64(&mut self) -> u64 {
self.state = self.state.wrapping_add(0x9E37_79B9_7F4A_7C15);
let mut z = self.state;
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
z ^ (z >> 31)
}
#[inline]
pub fn uniform(&mut self) -> f64 {
(self.next_u64() >> 11) as f64 / (1u64 << 53) as f64
}
#[inline]
pub fn uniform_in(&mut self, lo: f64, hi: f64) -> f64 {
lo + (hi - lo) * self.uniform()
}
#[inline]
pub fn normal(&mut self) -> f64 {
let u1 = (1.0 - self.uniform()).max(f64::MIN_POSITIVE); let u2 = self.uniform();
(-2.0 * u1.ln()).sqrt() * (2.0 * std::f64::consts::PI * u2).cos()
}
#[inline]
pub fn index(&mut self, bound: usize) -> usize {
debug_assert!(bound > 0);
(self.next_u64() % bound as u64) as usize
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn deterministic() {
let mut a = Rng::new(123);
let mut b = Rng::new(123);
for _ in 0..1000 {
assert_eq!(a.next_u64(), b.next_u64());
}
}
#[test]
fn uniform_in_range() {
let mut r = Rng::new(7);
for _ in 0..10_000 {
let x = r.uniform();
assert!((0.0..1.0).contains(&x));
}
}
#[test]
fn index_in_range() {
let mut r = Rng::new(9);
for _ in 0..10_000 {
assert!(r.index(13) < 13);
}
}
#[test]
fn split_streams_are_independent_and_reproducible() {
let mut s0a = Rng::split(42, 0);
let mut s0b = Rng::split(42, 0);
let mut s1 = Rng::split(42, 1);
assert_eq!(s0a.next_u64(), s0b.next_u64());
let a: Vec<u64> = (0..8).map(|_| s0a.next_u64()).collect();
let b: Vec<u64> = (0..8).map(|_| s1.next_u64()).collect();
assert_ne!(a, b);
}
#[test]
fn normal_is_roughly_standard() {
let mut r = Rng::new(2024);
let n = 100_000;
let mut mean = 0.0;
let mut m2 = 0.0;
for k in 1..=n {
let x = r.normal();
let d = x - mean;
mean += d / k as f64;
m2 += d * (x - mean);
}
let var = m2 / (n as f64 - 1.0);
assert!(mean.abs() < 0.02, "mean {mean}");
assert!((var - 1.0).abs() < 0.05, "var {var}");
}
}