| 1 | #![allow(clippy::unreadable_literal, clippy::upper_case_acronyms)] |
| 2 | |
| 3 | //! An MT19937 Mersenne Twister rng implementation, with the goal of being |
| 4 | //! compatible with CPython's `_random` module. |
| 5 | //! |
| 6 | //! This crate was translated from the original |
| 7 | //! [implementation](http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/MT2002/emt19937ar.html) |
| 8 | //! by a team at Hiroshima University. The original content of the header of |
| 9 | //! their implementation, along with the BSD-3 license, is left intact below. |
| 10 | //! |
| 11 | //! # mt19937ar.c header |
| 12 | |
| 13 | /*! |
| 14 | A C-program for MT19937, with initialization improved 2002/1/26. |
| 15 | Coded by Takuji Nishimura and Makoto Matsumoto. |
| 16 | |
| 17 | Before using, initialize the state by using init_genrand(seed) |
| 18 | or init_by_array(init_key, key_length). |
| 19 | |
| 20 | Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura, |
| 21 | All rights reserved. |
| 22 | |
| 23 | Redistribution and use in source and binary forms, with or without |
| 24 | modification, are permitted provided that the following conditions |
| 25 | are met: |
| 26 | |
| 27 | 1. Redistributions of source code must retain the above copyright |
| 28 | notice, this list of conditions and the following disclaimer. |
| 29 | |
| 30 | 2. Redistributions in binary form must reproduce the above copyright |
| 31 | notice, this list of conditions and the following disclaimer in the |
| 32 | documentation and/or other materials provided with the distribution. |
| 33 | |
| 34 | 3. The names of its contributors may not be used to endorse or promote |
| 35 | products derived from this software without specific prior written |
| 36 | permission. |
| 37 | |
| 38 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
| 39 | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
| 40 | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR |
| 41 | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR |
| 42 | CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, |
| 43 | EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, |
| 44 | PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR |
| 45 | PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF |
| 46 | LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING |
| 47 | NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS |
| 48 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
| 49 | |
| 50 | |
| 51 | Any feedback is very welcome. |
| 52 | |
| 53 | http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html |
| 54 | |
| 55 | email: m-mat @ math.sci.hiroshima-u.ac.jp (remove space) |
| 56 | */ |
| 57 | |
| 58 | // this was translated from c; all rights go to copyright holders listed above |
| 59 | // https://gist.github.com/coolreader18/b56d510f1b0551d2954d74ad289f7d2e |
| 60 | |
| 61 | /* Period parameters */ |
| 62 | const N: usize = 624; |
| 63 | const M: usize = 397; |
| 64 | const MATRIX_A: u32 = 0x9908b0dfu32; /* constant vector a */ |
| 65 | const UPPER_MASK: u32 = 0x80000000u32; /* most significant w-r bits */ |
| 66 | const LOWER_MASK: u32 = 0x7fffffffu32; /* least significant r bits */ |
| 67 | |
| 68 | /// rand::Rng instance implementing the mt19937 mersenne twister algorithm |
| 69 | pub struct MT19937 { |
| 70 | mt: [u32; N], /* the array for the state vector */ |
| 71 | mti: usize, /* mti==N+1 means mt[N] is not initialized */ |
| 72 | } |
| 73 | const MT19937_DEFAULT: MT19937 = MT19937 { |
| 74 | mt: [0; N], |
| 75 | mti: N + 1, |
| 76 | }; |
| 77 | impl Default for MT19937 { |
| 78 | #[inline] |
| 79 | fn default() -> Self { |
| 80 | MT19937_DEFAULT |
| 81 | } |
| 82 | } |
| 83 | impl std::fmt::Debug for MT19937 { |
| 84 | fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { |
| 85 | f.pad("MT19937") |
| 86 | } |
| 87 | } |
| 88 | |
| 89 | impl MT19937 { |
| 90 | #[inline] |
| 91 | pub fn new_with_slice_seed(init_key: &[u32]) -> Self { |
| 92 | let mut state = Self::default(); |
| 93 | state.seed_slice(init_key); |
| 94 | state |
| 95 | } |
| 96 | |
| 97 | /** initializes self.mt[N] with a seed */ |
| 98 | fn seed(&mut self, s: u32) { |
| 99 | self.mt[0] = s; |
| 100 | self.mti = 1; |
| 101 | while self.mti < N { |
| 102 | self.mt[self.mti] = 1812433253u32 |
| 103 | .wrapping_mul(self.mt[self.mti - 1] ^ (self.mt[self.mti - 1] >> 30)) |
| 104 | + self.mti as u32; |
| 105 | /* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */ |
| 106 | /* In the previous versions, MSBs of the seed affect */ |
| 107 | /* only MSBs of the array self.mt[]. */ |
| 108 | /* 2002/01/09 modified by Makoto Matsumoto */ |
| 109 | self.mti += 1; |
| 110 | } |
| 111 | } |
| 112 | |
| 113 | /** initialize by an array with array-length */ |
| 114 | /* init_key is the array for initializing keys */ |
| 115 | /* key_length is its length */ |
| 116 | /* slight change for C++, 2004/2/26 */ |
| 117 | pub fn seed_slice(&mut self, init_key: &[u32]) { |
| 118 | let mut i; |
| 119 | let mut j; |
| 120 | let mut k; |
| 121 | self.seed(19650218); |
| 122 | i = 1; |
| 123 | j = 0; |
| 124 | k = if N > init_key.len() { |
| 125 | N |
| 126 | } else { |
| 127 | init_key.len() |
| 128 | }; |
| 129 | while k != 0 { |
| 130 | self.mt[i] = (self.mt[i] |
| 131 | ^ ((self.mt[i - 1] ^ (self.mt[i - 1] >> 30)).wrapping_mul(1664525u32))) |
| 132 | .wrapping_add(init_key[j]) |
| 133 | .wrapping_add(j as u32); /* non linear */ |
| 134 | self.mt[i] &= 0xffffffffu32; /* for WORDSIZE > 32 machines */ |
| 135 | i += 1; |
| 136 | j += 1; |
| 137 | if i >= N { |
| 138 | self.mt[0] = self.mt[N - 1]; |
| 139 | i = 1; |
| 140 | } |
| 141 | if j >= init_key.len() { |
| 142 | j = 0; |
| 143 | } |
| 144 | k -= 1; |
| 145 | } |
| 146 | k = N - 1; |
| 147 | while k != 0 { |
| 148 | self.mt[i] = (self.mt[i] |
| 149 | ^ ((self.mt[i - 1] ^ (self.mt[i - 1] >> 30)).wrapping_mul(1566083941u32))) |
| 150 | .wrapping_sub(i as u32); /* non linear */ |
| 151 | self.mt[i] &= 0xffffffffu32; /* for WORDSIZE > 32 machines */ |
| 152 | i += 1; |
| 153 | if i >= N { |
| 154 | self.mt[0] = self.mt[N - 1]; |
| 155 | i = 1; |
| 156 | } |
| 157 | k -= 1; |
| 158 | } |
| 159 | |
| 160 | self.mt[0] = 0x80000000u32; /* MSB is 1; assuring non-zero initial array */ |
| 161 | } |
| 162 | |
| 163 | /** generates a random number on [0,0xffffffff]-interval */ |
| 164 | fn gen_u32(&mut self) -> u32 { |
| 165 | let mut y: u32; |
| 166 | let mag01 = |x| if (x & 0x1) == 1 { MATRIX_A } else { 0 }; |
| 167 | /* mag01[x] = x * MATRIX_A for x=0,1 */ |
| 168 | |
| 169 | if self.mti >= N { |
| 170 | /* generate N words at one time */ |
| 171 | |
| 172 | if self.mti == N + 1 |
| 173 | /* if seed() has not been called, */ |
| 174 | { |
| 175 | self.seed(5489u32); |
| 176 | } /* a default initial seed is used */ |
| 177 | |
| 178 | for kk in 0..N - M { |
| 179 | y = (self.mt[kk] & UPPER_MASK) | (self.mt[kk + 1] & LOWER_MASK); |
| 180 | self.mt[kk] = self.mt[kk + M] ^ (y >> 1) ^ mag01(y); |
| 181 | } |
| 182 | for kk in N - M..N - 1 { |
| 183 | y = (self.mt[kk] & UPPER_MASK) | (self.mt[kk + 1] & LOWER_MASK); |
| 184 | self.mt[kk] = self.mt[kk.wrapping_add(M.wrapping_sub(N))] ^ (y >> 1) ^ mag01(y); |
| 185 | } |
| 186 | y = (self.mt[N - 1] & UPPER_MASK) | (self.mt[0] & LOWER_MASK); |
| 187 | self.mt[N - 1] = self.mt[M - 1] ^ (y >> 1) ^ mag01(y); |
| 188 | |
| 189 | self.mti = 0; |
| 190 | } |
| 191 | |
| 192 | y = self.mt[self.mti]; |
| 193 | self.mti += 1; |
| 194 | |
| 195 | /* Tempering */ |
| 196 | y ^= y >> 11; |
| 197 | y ^= (y << 7) & 0x9d2c5680u32; |
| 198 | y ^= (y << 15) & 0xefc60000u32; |
| 199 | y ^= y >> 18; |
| 200 | |
| 201 | y |
| 202 | } |
| 203 | } |
| 204 | |
| 205 | /** generates a random number on [0,1) with 53-bit resolution*/ |
| 206 | /// |
| 207 | /// This generates a float with the same algorithm that CPython uses; calling |
| 208 | /// it with an [`MT19937`](struct.MT19937.html) with a given seed returns the same as it would in CPython. |
| 209 | /// |
| 210 | /// e.g.: |
| 211 | /// ``` |
| 212 | /// let mut m = mt19937::MT19937::new_with_slice_seed(&[12345]); |
| 213 | /// let expected: f64 = 0.416619872545341163316834354191087186336517333984375; |
| 214 | /// assert_eq!(mt19937::gen_res53(&mut m), expected); |
| 215 | /// ``` |
| 216 | /// and in Python: |
| 217 | /// ```python |
| 218 | /// import random |
| 219 | /// random.seed(12345) |
| 220 | /// expected = 0.416619872545341163316834354191087186336517333984375 |
| 221 | /// assert random.random() == expected |
| 222 | /// ``` |
| 223 | /// (note that CPython converts ints to slices by taking the native endian ordering |
| 224 | /// of the underlying "BigInt" implementation, but for seeds < u32::max_value(), |
| 225 | /// just `&[seed]` should be fine.) |
| 226 | /// |
| 227 | /// Original mt19937ar.c attribution: |
| 228 | /// |
| 229 | /** These real versions are due to Isaku Wada, 2002/01/09 added */ |
| 230 | pub fn gen_res53<R: rand_core::RngCore>(rng: &mut R) -> f64 { |
| 231 | let a = rng.next_u32() >> 5; |
| 232 | let b = rng.next_u32() >> 6; |
| 233 | (a as f64 * 67108864.0 + b as f64) * (1.0 / 9007199254740992.0) |
| 234 | } |
| 235 | |
| 236 | impl rand_core::RngCore for MT19937 { |
| 237 | #[inline] |
| 238 | fn next_u32(&mut self) -> u32 { |
| 239 | self.gen_u32() |
| 240 | } |
| 241 | #[inline] |
| 242 | fn next_u64(&mut self) -> u64 { |
| 243 | rand_core::impls::next_u64_via_u32(self) |
| 244 | } |
| 245 | #[inline] |
| 246 | fn fill_bytes(&mut self, dest: &mut [u8]) { |
| 247 | rand_core::impls::fill_bytes_via_next(self, dest) |
| 248 | } |
| 249 | #[inline] |
| 250 | fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), rand_core::Error> { |
| 251 | self.fill_bytes(dest); |
| 252 | Ok(()) |
| 253 | } |
| 254 | } |
| 255 | |
| 256 | /// Seed for <MT19937 as rand_core::SeedableRng> |
| 257 | /// |
| 258 | /// Very big seed, but this is the size that CPython uses as well |
| 259 | pub struct Seed(pub [u32; N]); |
| 260 | impl Default for Seed { |
| 261 | #[inline] |
| 262 | fn default() -> Self { |
| 263 | Seed([0; N]) |
| 264 | } |
| 265 | } |
| 266 | impl AsMut<[u8]> for Seed { |
| 267 | #[inline] |
| 268 | fn as_mut(&mut self) -> &mut [u8] { |
| 269 | // this will always get the full bytes, since align_of(u32) > align_of(u8) |
| 270 | unsafe { self.0.align_to_mut().1 } |
| 271 | } |
| 272 | } |
| 273 | impl rand_core::SeedableRng for MT19937 { |
| 274 | type Seed = Seed; |
| 275 | #[inline] |
| 276 | fn from_seed(seed: Self::Seed) -> Self { |
| 277 | Self::new_with_slice_seed(&seed.0[..]) |
| 278 | } |
| 279 | } |