-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlcg.rs
58 lines (43 loc) · 1.14 KB
/
lcg.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
// Linear Congruential Generator
use std::num::Wrapping;
pub struct LCG {
m: u64,
a: u64,
b: u64,
s: Wrapping<u64>,
}
impl LCG {
pub fn new(seed: u64, m: u64, a: u64, b: u64) -> Self {
Self {
m,
a,
b,
s: Wrapping(seed),
}
}
pub fn next(&mut self) -> u64 {
self.s = (self.s * Wrapping(self.a) + Wrapping(self.b)) % Wrapping(self.m);
self.s.0
}
}
impl Iterator for LCG {
type Item = u64;
fn next(&mut self) -> Option<u64> {
Some(self.next())
}
}
#[test]
fn test_lcg() {
let mut lcg = LCG::new(312, 100000, 70495, 24245);
let random_number = lcg.next();
assert_eq!(random_number, 18685);
let expected_numbers = vec![23320, 67645, 58520];
for (random_number, expected_number) in lcg.take(3).zip(expected_numbers) {
assert_eq!(random_number, expected_number);
}
let mut lcg = LCG::new(2u64.pow(10), 2u64.pow(32) - 1, 12345, 678910);
let random_number = lcg.next();
assert_eq!(random_number, 13320190);
let random_number = lcg.next();
assert_eq!(random_number, 1229667250);
}