tinymind/rand.rs
1//! A bit-exact re-implementation of glibc's `srand()`/`rand()`.
2//!
3//! tinymind (C++)'s examples (xor, iris, energy efficiency) draw their initial weights
4//! from `rand()` seeded with 1, then re-seed it with 7 for the shuffle and the
5//! training samples. Reproducing a C++ run bit-for-bit therefore needs the
6//! identical random sequences. glibc's default generator is the TYPE_3
7//! additive feedback generator: `r[i] = r[i-3] + r[i-31]` (mod 2^32), seeded by a
8//! Park-Miller LCG, with the first 310 outputs discarded and the low bit dropped.
9//!
10//! This is not part of tinymind (C++) itself; it exists so the examples can be compared
11//! against the C++ builds on Linux/glibc.
12
13/// glibc `rand()` state. `next()` returns values in `0..=0x7FFF_FFFF`, like `rand()`.
14#[derive(Clone, Debug)]
15pub struct GlibcRand {
16 /// Ring buffer holding the last 34 words of the `r[]` sequence.
17 ring: [u32; 34],
18 /// Index of the next word to produce, counted from the start of `r[]`.
19 pos: usize,
20}
21
22impl GlibcRand {
23 /// Equivalent to `srand(seed)`.
24 pub fn new(seed: u32) -> Self {
25 let mut r = [0i32; 34];
26 // glibc maps seed 0 to 1.
27 r[0] = if seed == 0 { 1 } else { seed as i32 };
28 for i in 1..31 {
29 // Park-Miller "minimal standard" LCG, 16807 * r mod (2^31 - 1), using
30 // Schrage's method so the product never overflows 32 bits.
31 let hi = r[i - 1] / 127_773;
32 let lo = r[i - 1] % 127_773;
33 let mut word = 16_807 * lo - 2_836 * hi;
34 if word < 0 {
35 word += 2_147_483_647;
36 }
37 r[i] = word;
38 }
39 for i in 31..34 {
40 r[i] = r[i - 31];
41 }
42
43 let mut rng = Self {
44 ring: r.map(|w| w as u32),
45 pos: 34,
46 };
47 // glibc discards the first 310 outputs (10 * the degree, 31).
48 for _ in 0..310 {
49 rng.step();
50 }
51 rng
52 }
53
54 /// Equivalent to `rand()`.
55 pub fn next_i32(&mut self) -> i32 {
56 (self.step() >> 1) as i32
57 }
58
59 fn step(&mut self) -> u32 {
60 let i = self.pos;
61 let word = self.ring[(i - 31) % 34].wrapping_add(self.ring[(i - 3) % 34]);
62 self.ring[i % 34] = word;
63 self.pos += 1;
64 word
65 }
66}
67
68#[cfg(test)]
69mod tests {
70 use super::*;
71
72 #[test]
73 fn matches_glibc_seed_1() {
74 // The well-known first outputs of glibc rand() with the default seed.
75 let mut rng = GlibcRand::new(1);
76 let expected = [
77 1_804_289_383,
78 846_930_886,
79 1_681_692_777,
80 1_714_636_915,
81 1_957_747_793,
82 ];
83 for e in expected {
84 assert_eq!(rng.next_i32(), e);
85 }
86 }
87}