rand_pcg/pcg128.rs
1// Copyright 2018 Developers of the Rand project.
2// Copyright 2017 Paul Dicker.
3// Copyright 2014-2017 Melissa O'Neill and PCG Project contributors
4//
5// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
8// option. This file may not be copied, modified, or distributed
9// except according to those terms.
10
11//! PCG random number generators
12
13// This is the default multiplier used by PCG for 128-bit state.
14const MULTIPLIER: u128 = 0x2360_ED05_1FC6_5DA4_4385_DF64_9FCC_F645;
15
16use core::fmt;
17use rand_core::{le, Error, RngCore, SeedableRng};
18#[cfg(feature = "serde1")] use serde::{Deserialize, Serialize};
19
20/// A PCG random number generator (XSL RR 128/64 (LCG) variant).
21///
22/// Permuted Congruential Generator with 128-bit state, internal Linear
23/// Congruential Generator, and 64-bit output via "xorshift low (bits),
24/// random rotation" output function.
25///
26/// This is a 128-bit LCG with explicitly chosen stream with the PCG-XSL-RR
27/// output function. This combination is the standard `pcg64`.
28///
29/// Despite the name, this implementation uses 32 bytes (256 bit) space
30/// comprising 128 bits of state and 128 bits stream selector. These are both
31/// set by `SeedableRng`, using a 256-bit seed.
32///
33/// Note that two generators with different stream parameters may be closely
34/// correlated.
35#[derive(Clone, PartialEq, Eq)]
36#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
37pub struct Lcg128Xsl64 {
38 state: u128,
39 increment: u128,
40}
41
42/// [`Lcg128Xsl64`] is also officially known as `pcg64`.
43pub type Pcg64 = Lcg128Xsl64;
44
45impl Lcg128Xsl64 {
46 /// Multi-step advance functions (jump-ahead, jump-back)
47 ///
48 /// The method used here is based on Brown, "Random Number Generation
49 /// with Arbitrary Stride,", Transactions of the American Nuclear
50 /// Society (Nov. 1994). The algorithm is very similar to fast
51 /// exponentiation.
52 ///
53 /// Even though delta is an unsigned integer, we can pass a
54 /// signed integer to go backwards, it just goes "the long way round".
55 ///
56 /// Using this function is equivalent to calling `next_64()` `delta`
57 /// number of times.
58 #[inline]
59 pub fn advance(&mut self, delta: u128) {
60 let mut acc_mult: u128 = 1;
61 let mut acc_plus: u128 = 0;
62 let mut cur_mult = MULTIPLIER;
63 let mut cur_plus = self.increment;
64 let mut mdelta = delta;
65
66 while mdelta > 0 {
67 if (mdelta & 1) != 0 {
68 acc_mult = acc_mult.wrapping_mul(cur_mult);
69 acc_plus = acc_plus.wrapping_mul(cur_mult).wrapping_add(cur_plus);
70 }
71 cur_plus = cur_mult.wrapping_add(1).wrapping_mul(cur_plus);
72 cur_mult = cur_mult.wrapping_mul(cur_mult);
73 mdelta /= 2;
74 }
75 self.state = acc_mult.wrapping_mul(self.state).wrapping_add(acc_plus);
76 }
77
78 /// Construct an instance compatible with PCG seed and stream.
79 ///
80 /// Note that two generators with different stream parameters may be closely
81 /// correlated.
82 ///
83 /// PCG specifies the following default values for both parameters:
84 ///
85 /// - `state = 0xcafef00dd15ea5e5`
86 /// - `stream = 0xa02bdbf7bb3c0a7ac28fa16a64abf96`
87 pub fn new(state: u128, stream: u128) -> Self {
88 // The increment must be odd, hence we discard one bit:
89 let increment = (stream << 1) | 1;
90 Lcg128Xsl64::from_state_incr(state, increment)
91 }
92
93 #[inline]
94 fn from_state_incr(state: u128, increment: u128) -> Self {
95 let mut pcg = Lcg128Xsl64 { state, increment };
96 // Move away from inital value:
97 pcg.state = pcg.state.wrapping_add(pcg.increment);
98 pcg.step();
99 pcg
100 }
101
102 #[inline]
103 fn step(&mut self) {
104 // prepare the LCG for the next round
105 self.state = self
106 .state
107 .wrapping_mul(MULTIPLIER)
108 .wrapping_add(self.increment);
109 }
110}
111
112// Custom Debug implementation that does not expose the internal state
113impl fmt::Debug for Lcg128Xsl64 {
114 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
115 write!(f, "Lcg128Xsl64 {{}}")
116 }
117}
118
119/// We use a single 255-bit seed to initialise the state and select a stream.
120/// One `seed` bit (lowest bit of `seed[8]`) is ignored.
121impl SeedableRng for Lcg128Xsl64 {
122 type Seed = [u8; 32];
123
124 fn from_seed(seed: Self::Seed) -> Self {
125 let mut seed_u64 = [0u64; 4];
126 le::read_u64_into(&seed, &mut seed_u64);
127 let state = u128::from(seed_u64[0]) | (u128::from(seed_u64[1]) << 64);
128 let incr = u128::from(seed_u64[2]) | (u128::from(seed_u64[3]) << 64);
129
130 // The increment must be odd, hence we discard one bit:
131 Lcg128Xsl64::from_state_incr(state, incr | 1)
132 }
133}
134
135impl RngCore for Lcg128Xsl64 {
136 #[inline]
137 fn next_u32(&mut self) -> u32 {
138 self.next_u64() as u32
139 }
140
141 #[inline]
142 fn next_u64(&mut self) -> u64 {
143 self.step();
144 output_xsl_rr(self.state)
145 }
146
147 #[inline]
148 fn fill_bytes(&mut self, dest: &mut [u8]) {
149 fill_bytes_impl(self, dest)
150 }
151
152 #[inline]
153 fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> {
154 self.fill_bytes(dest);
155 Ok(())
156 }
157}
158
159
160/// A PCG random number generator (XSL 128/64 (MCG) variant).
161///
162/// Permuted Congruential Generator with 128-bit state, internal Multiplicative
163/// Congruential Generator, and 64-bit output via "xorshift low (bits),
164/// random rotation" output function.
165///
166/// This is a 128-bit MCG with the PCG-XSL-RR output function, also known as
167/// `pcg64_fast`.
168/// Note that compared to the standard `pcg64` (128-bit LCG with PCG-XSL-RR
169/// output function), this RNG is faster, also has a long cycle, and still has
170/// good performance on statistical tests.
171#[derive(Clone, PartialEq, Eq)]
172#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
173pub struct Mcg128Xsl64 {
174 state: u128,
175}
176
177/// A friendly name for [`Mcg128Xsl64`] (also known as `pcg64_fast`).
178pub type Pcg64Mcg = Mcg128Xsl64;
179
180impl Mcg128Xsl64 {
181 /// Multi-step advance functions (jump-ahead, jump-back)
182 ///
183 /// The method used here is based on Brown, "Random Number Generation
184 /// with Arbitrary Stride,", Transactions of the American Nuclear
185 /// Society (Nov. 1994). The algorithm is very similar to fast
186 /// exponentiation.
187 ///
188 /// Even though delta is an unsigned integer, we can pass a
189 /// signed integer to go backwards, it just goes "the long way round".
190 ///
191 /// Using this function is equivalent to calling `next_64()` `delta`
192 /// number of times.
193 #[inline]
194 pub fn advance(&mut self, delta: u128) {
195 let mut acc_mult: u128 = 1;
196 let mut acc_plus: u128 = 0;
197 let mut cur_mult = MULTIPLIER;
198 let mut cur_plus: u128 = 0;
199 let mut mdelta = delta;
200
201 while mdelta > 0 {
202 if (mdelta & 1) != 0 {
203 acc_mult = acc_mult.wrapping_mul(cur_mult);
204 acc_plus = acc_plus.wrapping_mul(cur_mult).wrapping_add(cur_plus);
205 }
206 cur_plus = cur_mult.wrapping_add(1).wrapping_mul(cur_plus);
207 cur_mult = cur_mult.wrapping_mul(cur_mult);
208 mdelta /= 2;
209 }
210 self.state = acc_mult.wrapping_mul(self.state).wrapping_add(acc_plus);
211 }
212
213 /// Construct an instance compatible with PCG seed.
214 ///
215 /// Note that PCG specifies a default value for the parameter:
216 ///
217 /// - `state = 0xcafef00dd15ea5e5`
218 pub fn new(state: u128) -> Self {
219 // Force low bit to 1, as in C version (C++ uses `state | 3` instead).
220 Mcg128Xsl64 { state: state | 1 }
221 }
222}
223
224// Custom Debug implementation that does not expose the internal state
225impl fmt::Debug for Mcg128Xsl64 {
226 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
227 write!(f, "Mcg128Xsl64 {{}}")
228 }
229}
230
231/// We use a single 126-bit seed to initialise the state and select a stream.
232/// Two `seed` bits (lowest order of last byte) are ignored.
233impl SeedableRng for Mcg128Xsl64 {
234 type Seed = [u8; 16];
235
236 fn from_seed(seed: Self::Seed) -> Self {
237 // Read as if a little-endian u128 value:
238 let mut seed_u64 = [0u64; 2];
239 le::read_u64_into(&seed, &mut seed_u64);
240 let state = u128::from(seed_u64[0]) |
241 u128::from(seed_u64[1]) << 64;
242 Mcg128Xsl64::new(state)
243 }
244}
245
246impl RngCore for Mcg128Xsl64 {
247 #[inline]
248 fn next_u32(&mut self) -> u32 {
249 self.next_u64() as u32
250 }
251
252 #[inline]
253 fn next_u64(&mut self) -> u64 {
254 self.state = self.state.wrapping_mul(MULTIPLIER);
255 output_xsl_rr(self.state)
256 }
257
258 #[inline]
259 fn fill_bytes(&mut self, dest: &mut [u8]) {
260 fill_bytes_impl(self, dest)
261 }
262
263 #[inline]
264 fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> {
265 self.fill_bytes(dest);
266 Ok(())
267 }
268}
269
270#[inline(always)]
271fn output_xsl_rr(state: u128) -> u64 {
272 // Output function XSL RR ("xorshift low (bits), random rotation")
273 // Constants are for 128-bit state, 64-bit output
274 const XSHIFT: u32 = 64; // (128 - 64 + 64) / 2
275 const ROTATE: u32 = 122; // 128 - 6
276
277 let rot = (state >> ROTATE) as u32;
278 let xsl = ((state >> XSHIFT) as u64) ^ (state as u64);
279 xsl.rotate_right(rot)
280}
281
282#[inline(always)]
283fn fill_bytes_impl<R: RngCore + ?Sized>(rng: &mut R, dest: &mut [u8]) {
284 let mut left = dest;
285 while left.len() >= 8 {
286 let (l, r) = { left }.split_at_mut(8);
287 left = r;
288 let chunk: [u8; 8] = rng.next_u64().to_le_bytes();
289 l.copy_from_slice(&chunk);
290 }
291 let n = left.len();
292 if n > 0 {
293 let chunk: [u8; 8] = rng.next_u64().to_le_bytes();
294 left.copy_from_slice(&chunk[..n]);
295 }
296}