32 lines
940 B
Rust
32 lines
940 B
Rust
//! SplitMix64 as a value: every call returns the number *and* the next generator.
|
|
|
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
|
pub struct Rng {
|
|
state: u64,
|
|
}
|
|
|
|
impl Rng {
|
|
pub const fn seeded(seed: u64) -> Rng {
|
|
Rng { state: seed }
|
|
}
|
|
|
|
pub fn next_u64(self) -> (u64, Rng) {
|
|
let state = self.state.wrapping_add(0x9E37_79B9_7F4A_7C15);
|
|
let z = (state ^ (state >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
|
|
let z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
|
|
(z ^ (z >> 31), Rng { state })
|
|
}
|
|
|
|
/// Uniform in `0..bound`; `bound == 0` yields 0.
|
|
pub fn below(self, bound: u64) -> (u64, Rng) {
|
|
let (x, next) = self.next_u64();
|
|
(((x as u128 * bound as u128) >> 64) as u64, next)
|
|
}
|
|
|
|
/// Uniform in `[0, 1)`.
|
|
pub fn unit(self) -> (f64, Rng) {
|
|
let (x, next) = self.next_u64();
|
|
((x >> 11) as f64 / (1u64 << 53) as f64, next)
|
|
}
|
|
}
|