-
Notifications
You must be signed in to change notification settings - Fork 2
/
m21.py
executable file
·49 lines (42 loc) · 1.31 KB
/
m21.py
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
#!/usr/bin/env python3
"""The Mersenne Twister"""
class MT19937:
u = 11
s, b = 7, 0x9d2c5680
t, c = 15, 0xefc60000
l = 18
def __init__(self, seed: int) -> None:
self.index = 624
self.state = [0] * 624
self.state[0] = seed & 0xffffffff
for i in range(1, 624):
self.state[i] = 0x6c078965 \
* (self.state[i - 1] ^ self.state[i - 1] >> 30) \
+ i & 0xffffffff
@staticmethod
def temper(y: int) -> int:
y ^= y >> MT19937.u
y ^= y << MT19937.s & MT19937.b
y ^= y << MT19937.t & MT19937.c
y ^= y >> MT19937.l
return y
def random(self) -> int:
if self.index >= 624:
self._twist()
y = self.temper(self.state[self.index])
self.index += 1
return y
def _twist(self) -> None:
for i in range(624):
y = (self.state[i] & 0x80000000) \
+ (self.state[(i + 1) % 624] & 0x7fffffff)
self.state[i] = self.state[(i + 397) % 624] ^ y >> 1
if y % 2 != 0:
self.state[i] ^= 0x9908b0df
self.index = 0
def main() -> None:
x = MT19937(5489) # Seed from mt19937ar.c
for _ in range(1000):
print(x.random())
if __name__ == "__main__":
main()