1#[derive(Clone, Debug, PartialEq, Eq)]
11pub struct Xoshiro256 {
12 s: [u64; 4],
13}
14
15const GFORTRAN_KEYS: [u64; 4] =
17 [0xbd0c5b6e50c2df49, 0xd46061cd46e1df38, 0xbb4f4d4ed6103544, 0x114a583d0756ad39];
18
19fn splitmix64(state: &mut u64) -> u64 {
20 *state = state.wrapping_add(0x9e3779b97f4a7c15);
21 let mut z = *state;
22 z = (z ^ (z >> 30)).wrapping_mul(0xbf58476d1ce4e5b9);
23 z = (z ^ (z >> 27)).wrapping_mul(0x94d049bb133111eb);
24 z ^ (z >> 31)
25}
26
27impl Xoshiro256 {
28 pub fn seed_from_u64(seed: u64) -> Self {
31 let mut sm = seed;
32 Self { s: [splitmix64(&mut sm), splitmix64(&mut sm), splitmix64(&mut sm), splitmix64(&mut sm)] }
33 }
34
35 pub fn gfortran_put(put: [i32; 8]) -> Self {
38 let w = |k: usize| put[k] as u32 as u64;
41 let raw = [w(7) | w(6) << 32, w(5) | w(4) << 32, w(3) | w(2) << 32, w(1) | w(0) << 32];
42 Self { s: std::array::from_fn(|i| raw[i] ^ GFORTRAN_KEYS[i]) }
43 }
44
45 pub fn gfortran(seed: i32) -> Self {
48 Self::gfortran_put([seed; 8])
49 }
50
51 pub fn next_u64(&mut self) -> u64 {
53 let s = &mut self.s;
54 let result = s[1].wrapping_mul(5).rotate_left(7).wrapping_mul(9);
55 let t = s[1] << 17;
56 s[2] ^= s[0];
57 s[3] ^= s[1];
58 s[1] ^= s[2];
59 s[0] ^= s[3];
60 s[2] ^= t;
61 s[3] = s[3].rotate_left(45);
62 result
63 }
64
65 pub fn uniform(&mut self) -> f64 {
68 (self.next_u64() >> 11) as f64 * (1.0 / (1u64 << 53) as f64)
69 }
70
71 pub fn uniforms(&mut self, n: usize) -> Vec<f64> {
73 (0..n).map(|_| self.uniform()).collect()
74 }
75
76 pub fn integer(&mut self, lo: usize, hi: usize) -> usize {
79 lo + ((hi - lo + 1) as f64 * self.uniform()) as usize
80 }
81}
82
83#[cfg(test)]
84mod tests {
85 use super::*;
86
87 #[test]
89 #[allow(clippy::excessive_precision)]
90 fn reproduces_gfortran() {
91 let mut r = Xoshiro256::gfortran(12345);
92 let expected = [
93 4.65636743897908767e-01,
94 1.00833111555351462e-01,
95 8.41914420882911130e-01,
96 7.73831493534653414e-01,
97 1.80372332904081167e-01,
98 8.44873831312145440e-01,
99 ];
100 for e in expected {
101 assert_eq!(r.uniform(), e);
102 }
103 assert_eq!(Xoshiro256::gfortran(1237).uniform(), 4.72208155982870581e-01);
104 assert_eq!(Xoshiro256::gfortran_put([1, 2, 3, 4, 5, 6, 7, 8]).uniform(), 4.71070899360821249e-01);
105 }
106
107 #[test]
108 fn seeds_differ() {
109 let a = Xoshiro256::seed_from_u64(1).uniforms(4);
110 let b = Xoshiro256::seed_from_u64(2).uniforms(4);
111 assert_ne!(a, b);
112 assert!(a.iter().all(|x| (0.0..1.0).contains(x)));
113 }
114}