neurons/random.rs
1// Copyright (C) 2024 Hallvard Høyland Lavik
2
3/// A linear congruential generator. [Source.](https://en.wikipedia.org/wiki/Linear_congruential_generator)
4///
5/// # Formula
6///
7/// * `X_{n+1} = (multiplier * X_n + increment) % modulus`
8/// * `value = (X_{n+1} / (modulus - 1)) * (min - max) + min`
9///
10/// # Attributes
11///
12/// * `seed` - The initial value.
13/// * `modulus` - The modulus.
14/// * `multiplier` - The multiplier.
15/// * `increment` - The increment.
16/// * `current` - The current value.
17pub struct Generator {
18 modulus: u64,
19 multiplier: u64,
20 increment: u64,
21
22 current: u64,
23}
24
25impl Generator {
26 /// Creates a new linear congruential generator using C++11's `minstd_rand` parameters.
27 ///
28 /// # Arguments
29 ///
30 /// * `seed` - The initial value.
31 /// * `modulus` - The modulus.
32 /// * `multiplier` - The multiplier.
33 /// * `increment` - The increment.
34 /// * `current` - The current value.
35 ///
36 /// # Returns
37 ///
38 /// A new linear congruential generator.
39 pub fn create(seed: u64) -> Self {
40 Self {
41 modulus: 2u64.pow(31) - 1,
42 multiplier: 48271,
43 increment: 0,
44 current: seed,
45 }
46 }
47
48 /// Generates the next random number.
49 ///
50 /// # Formula
51 ///
52 /// * `X_{n+1} = (aX_n + c) mod m`
53 /// * `value = X_{n+1} / (m - 1) * (min - max) + min`
54 ///
55 /// # Returns
56 ///
57 /// The next random number (`value`).
58 pub fn generate(&mut self, min: f32, max: f32) -> f32 {
59 self.current = (self.multiplier * self.current + self.increment) % self.modulus;
60
61 (self.current as f32 / (self.modulus - 1) as f32) * (max - min) + min
62 }
63
64 /// Shuffles the given values inplace.
65 ///
66 /// # Arguments
67 ///
68 /// * `values` - The values to shuffle.
69 ///
70 /// # Example
71 ///
72 /// ```
73 /// use neurons::random;
74 ///
75 /// let mut generator = random::Generator::create(12345);
76 /// let mut values = vec![1, 2, 3, 4, 5];
77 /// generator.shuffle(&mut values);
78 /// println!("{:?}", values);
79 /// ```
80 pub fn shuffle(&mut self, values: &mut Vec<usize>) {
81 for i in 0..values.len() {
82 let j = self.generate(0.0, values.len() as f32) as usize;
83 values.swap(i, j);
84 }
85 }
86}