evolutionary_planning/
rng.rs1use core::convert::Infallible;
10
11use rand_core::Rng;
12
13#[derive(Debug, Clone, PartialEq, Eq)]
25pub struct SplitMix64 {
26 state: u64,
28}
29
30impl SplitMix64 {
31 #[must_use]
33 pub const fn new(seed: u64) -> Self {
34 Self { state: seed }
35 }
36
37 fn next_word(&mut self) -> u64 {
39 self.state = self.state.wrapping_add(0x9E37_79B9_7F4A_7C15);
40 let mut z = self.state;
41 z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
42 z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
43
44 z ^ (z >> 31)
45 }
46
47 #[must_use]
50 pub fn fork(&self, stream: u64) -> Self {
51 let mixed = Self::new(self.state ^ stream.wrapping_mul(0xD1B5_4A32_D192_ED03)).next_word();
52
53 Self::new(mixed)
54 }
55}
56
57impl rand_core::TryRng for SplitMix64 {
58 type Error = Infallible;
59
60 fn try_next_u32(&mut self) -> Result<u32, Infallible> {
61 Ok((self.next_word() >> 32) as u32)
62 }
63
64 fn try_next_u64(&mut self) -> Result<u64, Infallible> {
65 Ok(self.next_word())
66 }
67
68 fn try_fill_bytes(&mut self, dst: &mut [u8]) -> Result<(), Infallible> {
69 rand_core::utils::fill_bytes_via_next_word(dst, || self.try_next_u64())
70 }
71}
72
73pub fn unit_f64<R: Rng + ?Sized>(rng: &mut R) -> f64 {
83 const SCALE: f64 = 1.0 / 9_007_199_254_740_992.0;
85
86 #[expect(
87 clippy::cast_precision_loss,
88 reason = "the value has at most 53 bits, which f64 represents exactly"
89 )]
90 let bits = (rng.next_u64() >> 11) as f64;
91
92 bits * SCALE
93}
94
95pub fn uniform<R: Rng + ?Sized>(rng: &mut R, low: f64, high: f64) -> f64 {
97 if high <= low {
98 return low;
99 }
100
101 let x = low + (high - low) * unit_f64(rng);
102
103 if x >= high { low } else { x }
105}
106
107pub fn chance<R: Rng + ?Sized>(rng: &mut R, p: f64) -> bool {
109 if p >= 1.0 {
110 return true;
111 }
112
113 unit_f64(rng) < p
114}
115
116pub fn below<R: Rng + ?Sized>(rng: &mut R, n: usize) -> usize {
129 assert!(n > 0, "below(0) has no valid result");
130
131 let n = n as u64;
132 let mut product = u128::from(rng.next_u64()) * u128::from(n);
133
134 #[expect(
135 clippy::cast_possible_truncation,
136 reason = "the low half of a 128-bit product"
137 )]
138 let mut low = product as u64;
139 if low < n {
140 let threshold = n.wrapping_neg() % n;
141 while low < threshold {
142 product = u128::from(rng.next_u64()) * u128::from(n);
143
144 #[expect(
145 clippy::cast_possible_truncation,
146 reason = "the low half of a 128-bit product"
147 )]
148 {
149 low = product as u64;
150 }
151 }
152 }
153
154 #[expect(
155 clippy::cast_possible_truncation,
156 reason = "the high half is below n, a usize"
157 )]
158 let index = (product >> 64) as usize;
159
160 index
161}
162
163pub fn standard_normal<R: Rng + ?Sized>(rng: &mut R) -> f64 {
168 loop {
169 let u = 2.0 * unit_f64(rng) - 1.0;
170 let v = 2.0 * unit_f64(rng) - 1.0;
171 let s = u * u + v * v;
172 if s > 0.0 && s < 1.0 {
173 return u * libm::sqrt(-2.0 * libm::log(s) / s);
174 }
175 }
176}
177
178pub fn shuffle<T, R: Rng + ?Sized>(rng: &mut R, items: &mut [T]) {
180 for i in (1..items.len()).rev() {
181 let j = below(rng, i + 1);
182 items.swap(i, j);
183 }
184}
185
186pub fn two_sorted_indices<R: Rng + ?Sized>(rng: &mut R, n: usize) -> (usize, usize) {
192 assert!(n >= 2, "two distinct indices need n >= 2");
193
194 let a = below(rng, n);
195 let mut b = below(rng, n - 1);
196 if b >= a {
197 b += 1;
198 }
199
200 (a.min(b), a.max(b))
201}
202
203pub fn distinct_indices<R: Rng + ?Sized>(
210 rng: &mut R,
211 n: usize,
212 count: usize,
213 exclude: Option<usize>,
214) -> alloc::vec::Vec<usize> {
215 let mut pool: alloc::vec::Vec<usize> = (0..n).filter(|&i| Some(i) != exclude).collect();
216 assert!(pool.len() >= count, "not enough distinct indices");
217
218 for i in 0..count {
219 let j = i + below(rng, pool.len() - i);
220 pool.swap(i, j);
221 }
222
223 pool.truncate(count);
224 pool
225}
226
227#[cfg(test)]
228mod tests {
229 use super::*;
230
231 #[test]
233 fn matches_reference_sequence() {
234 let mut rng = SplitMix64::new(0);
235
236 assert_eq!(rng.next_u64(), 0xE220_A839_7B1D_CDAF);
237 assert_eq!(rng.next_u64(), 0x6E78_9E6A_A1B9_65F4);
238 }
239
240 #[test]
242 fn below_covers_range() {
243 let mut rng = SplitMix64::new(5);
244 let mut seen = [false; 7];
245 for _ in 0..1000 {
246 seen[below(&mut rng, 7)] = true;
247 }
248
249 assert!(seen.iter().all(|&s| s));
250 }
251
252 #[test]
254 fn normal_moments() {
255 let mut rng = SplitMix64::new(11);
256 let n = 20_000;
257 let samples: alloc::vec::Vec<f64> = (0..n).map(|_| standard_normal(&mut rng)).collect();
258 let mean = samples.iter().sum::<f64>() / f64::from(n);
259 let var = samples.iter().map(|x| (x - mean) * (x - mean)).sum::<f64>() / f64::from(n);
260
261 assert!(mean.abs() < 0.03, "mean {mean}");
262 assert!((var - 1.0).abs() < 0.05, "variance {var}");
263 }
264
265 #[test]
267 fn shuffle_and_pairs() {
268 let mut rng = SplitMix64::new(2);
269 let mut items: alloc::vec::Vec<u32> = (0..50).collect();
270 shuffle(&mut rng, &mut items);
271 let mut sorted = items.clone();
272 sorted.sort_unstable();
273
274 assert_eq!(sorted, (0..50).collect::<alloc::vec::Vec<_>>());
275 for _ in 0..100 {
276 let (a, b) = two_sorted_indices(&mut rng, 3);
277 assert!(a < b && b < 3);
278 }
279
280 let picked = distinct_indices(&mut rng, 6, 5, Some(2));
281 assert_eq!(picked.len(), 5);
282 assert!(!picked.contains(&2));
283 }
284
285 #[test]
287 fn forks_are_distinct() {
288 let base = SplitMix64::new(9);
289
290 assert_ne!(base.fork(0), base.fork(1));
291 assert_eq!(base.fork(3), base.fork(3));
292 }
293}