xorshift64star
This commit is contained in:
parent
119b49e20d
commit
56faa52d0d
|
@ -9,6 +9,7 @@ extern crate std;
|
||||||
pub mod cachepadded;
|
pub mod cachepadded;
|
||||||
pub mod drop_guard;
|
pub mod drop_guard;
|
||||||
pub mod ptr;
|
pub mod ptr;
|
||||||
|
pub mod rand;
|
||||||
#[cfg(feature = "alloc")]
|
#[cfg(feature = "alloc")]
|
||||||
pub mod smallbox;
|
pub mod smallbox;
|
||||||
pub mod util;
|
pub mod util;
|
||||||
|
|
32
src/rand.rs
Normal file
32
src/rand.rs
Normal file
|
@ -0,0 +1,32 @@
|
||||||
|
use core::cell::Cell;
|
||||||
|
|
||||||
|
/// A simple implementation of the XorShift64* pseudorandom number generator (PRNG).
|
||||||
|
/// Based on the algorithm described by George Marsaglia.
|
||||||
|
pub struct XorShift64Star {
|
||||||
|
state: Cell<u64>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl XorShift64Star {
|
||||||
|
/// Initializes the prng with a seed. Provided seed must be nonzero.
|
||||||
|
pub fn new(seed: u64) -> Self {
|
||||||
|
XorShift64Star {
|
||||||
|
state: Cell::new(seed),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns a pseudorandom number.
|
||||||
|
pub fn next(&self) -> u64 {
|
||||||
|
let mut x = self.state.get();
|
||||||
|
debug_assert_ne!(x, 0);
|
||||||
|
x ^= x >> 12;
|
||||||
|
x ^= x << 25;
|
||||||
|
x ^= x >> 27;
|
||||||
|
self.state.set(x);
|
||||||
|
x.wrapping_mul(0x2545_f491_4f6c_dd1d)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Return a pseudorandom number from `0..n`.
|
||||||
|
pub fn next_usize(&self, n: usize) -> usize {
|
||||||
|
(self.next() % n as u64) as usize
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in a new issue