Skip to main content

lib_jsl_random/
xoshiro256plusplus.rs

1//! The xoshiro256++ generator of Blackman and Vigna.
2//!
3//! See the book entry [Pseudo-random number generators](https://jwkunz.github.io/lib_jsl/book/random/generators.html#xoshiro256).
4
5use crate::split_mix_64::SplitMix64;
6use crate::uniform_generator::UniformGenerator;
7use lib_jsl_core::ErrorsJSL;
8/// xoshiro256++
9///
10/// High-quality, fast pseudorandom number generator suitable for
11/// Monte Carlo simulation and numerical work.
12///
13/// NOT cryptographically secure.
14///
15/// Reference:
16///   David Blackman & Sebastiano Vigna
17///   <https://prng.di.unimi.it/xoshiro256plusplus.c>
18#[derive(Clone, Debug)]
19pub struct Xoshiro256PlusPlus {
20    s: [u64; 4],
21}
22
23impl Xoshiro256PlusPlus {
24    /// Rotate left (safe wrapper)
25    #[inline(always)]
26    fn rotl(x: u64, k: u32) -> u64 {
27        x.rotate_left(k)
28    }
29
30    /// Create a new generator from a 256-bit seed (4 u64 values).
31    pub fn from_array_seed(seed: [u64; 4]) -> Result<Self,ErrorsJSL> {
32        if seed == [0, 0, 0, 0]{
33            Err(ErrorsJSL::InvalidInputRange("xoshiro256++ state must not be all zero"))
34        }else{
35            Ok(Self { s: seed })
36        }
37    }
38
39    /// Seed using SplitMix64 (recommended).
40    pub fn from_seed(seed: u64) -> Self {
41        let mut sm64 = SplitMix64::new(seed);
42        Self::from_array_seed([
43            sm64.next_u64(),
44            sm64.next_u64(),
45            sm64.next_u64(),
46            sm64.next_u64(),
47        ]).expect("SplitMix64 prevents zero seeds")
48    }
49
50    /// Seed using the current system time (not recommended for reproducibility).
51    pub fn from_random_seed() -> Self {
52        use std::time::{SystemTime, UNIX_EPOCH};
53        let seed = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time went backwards").as_nanos() as u64;
54        Self::from_seed(seed)
55    }
56
57    /// Jump ahead 2^128 steps (for parallel streams).
58    pub fn jump(&mut self) {
59        const JUMP: [u64; 4] = [
60            0x180ec6d33cfd0aba,
61            0xd5a61266f0c9392c,
62            0xa9582618e03fc9aa,
63            0x39abdc4529b1661c,
64        ];
65
66        let mut s0 = 0;
67        let mut s1 = 0;
68        let mut s2 = 0;
69        let mut s3 = 0;
70
71        for &jump in &JUMP {
72            for b in 0..64 {
73                if (jump & (1u64 << b)) != 0 {
74                    s0 ^= self.s[0];
75                    s1 ^= self.s[1];
76                    s2 ^= self.s[2];
77                    s3 ^= self.s[3];
78                }
79                self.next_u64();
80            }
81        }
82
83        self.s = [s0, s1, s2, s3];
84    }
85}
86
87impl UniformGenerator for Xoshiro256PlusPlus{
88    // ANCHOR: xoshiro
89    /// Generate next random u64.
90    fn next_u64(&mut self) -> u64 {
91        let result = Self::rotl(self.s[0].wrapping_add(self.s[3]), 23)
92            .wrapping_add(self.s[0]);
93
94        let t = self.s[1] << 17;
95
96        self.s[2] ^= self.s[0];
97        self.s[3] ^= self.s[1];
98        self.s[1] ^= self.s[2];
99        self.s[0] ^= self.s[3];
100
101        self.s[2] ^= t;
102        self.s[3] = Self::rotl(self.s[3], 45);
103
104        result
105    }
106    // ANCHOR_END: xoshiro
107
108    /// Generate a floating-point value in [0, 1).
109    ///
110    /// Uses the high 53 bits for correct uniformity.
111    fn next_f64(&mut self) -> f64 {
112        const SCALE: f64 = 1.0 / (1u64 << 53) as f64;
113        ((self.next_u64() >> 11) as f64) * SCALE
114    }
115}
116
117#[cfg(test)]
118mod test{
119    use super::*;
120    #[test]
121    fn test_xoshiro256plusplus(){
122            let mut rng = Xoshiro256PlusPlus::from_seed(0xdead_beef_cafe_f00d);
123            let mut rng2 = rng.clone();
124            rng.jump();
125            let correlation_depth : usize = 1_000_000;
126            let mut correlation = 0.0;
127            for _ in 0..correlation_depth{
128                let a = rng.next_f64();
129                let b = rng2.next_f64();
130                correlation += a*b;
131            }   
132            
133            correlation = correlation/correlation_depth as f64 - 0.25;           
134            assert!(correlation < 1E-4);        
135    }
136}