Last active
August 24, 2024 04:36
-
-
Save sertdfyguhi/e1f5f72e491ae653b86ca37e39ee6848 to your computer and use it in GitHub Desktop.
Implementation of Mersenne Twister in Python.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Implementation of MT19973 in Python. | |
class MersenneTwister: | |
def __init__(self, seed: int) -> None: | |
""" | |
Implementation of the Mersenne Twister algorithm. | |
Parameters: | |
seed: int | |
Seed to initialize Mersenne Twister. | |
""" | |
self.mt = [seed] | |
self.i = 0 | |
for i in range(1, 624): | |
t = 1812433253 * (self.mt[i - 1] ^ (self.mt[i - 1] >> 30)) + i | |
t = t & 0xFFFFFFFF # Gets the lower 32 bits of the number. | |
self.mt.append(t) | |
def twist(self) -> None: | |
"""Twists the internal state array.""" | |
for i in range(624): | |
y = (self.mt[i] & 0x80000000) + (self.mt[(i + 1) % 624] & 0x7FFFFFFF) | |
self.mt[i] = self.mt[(i + 397) % 624] ^ (y >> 1) | |
# Test if y is odd. | |
if y & 1 == 1: | |
self.mt[i] ^= 0x9908B0DF | |
def generate(self) -> int: | |
"""Generates a pseudo-random number.""" | |
if self.i == 0: | |
self.twist() | |
y = self.mt[self.i] | |
y ^= y >> 11 | |
y ^= (y << 7) & 0x9D2C5680 | |
y ^= (y << 15) & 0xEFC60000 | |
y ^= y >> 18 | |
# Sets the next index. | |
self.i = (self.i + 1) % 624 | |
return y | |
mt = MersenneTwister(0) | |
print(mt.generate()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment