Last active
November 10, 2015 15:23
-
-
Save natmchugh/769c530d30092c479ff7 to your computer and use it in GitHub Desktop.
Python implementation of the err interesting PHP internal implementation of mt_rand
This file contains 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
def _int32(x): | |
# Get the 32 least significant bits. | |
return int(0xFFFFFFFF & x) | |
class MT19937: | |
def __init__(self, seed): | |
# Initialize the index to 0 | |
self.index = 624 | |
self.mt = [0] * 624 | |
self.mt[0] = seed # Initialize the initial state to the seed | |
for i in range(1, 624): | |
self.mt[i] = _int32( | |
1812433253 * (self.mt[i - 1] ^ self.mt[i - 1] >> 30) + i) | |
def extract_number(self): | |
if self.index >= 624: | |
self.twist() | |
y = self.mt[self.index] | |
# Right shift by 11 bits | |
y = y ^ y >> 11 | |
# Shift y left by 7 and take the bitwise and of 0x9D2C5680 | |
y = y ^ y << 7 & 0x9D2C5680 | |
# Shift y left by 15 and take the bitwise and of y and 0xEFC60000 | |
y = y ^ y << 15 & 0xEFC60000 | |
# Right shift by 18 bits | |
y = y ^ y >> 18 | |
self.index += 1 | |
return y | |
def twist(self): | |
for i in range(0, 624): | |
# print self.mt[i] | |
# Get the most significant bit and add it to the less significant | |
# bits of the next number | |
z = self.mt[i] | |
y = _int32((self.mt[i] & 0x80000000) + | |
(self.mt[(i + 1) % 624] & 0x7fffffff)) | |
self.mt[i] = self.mt[(i + 397) % 624] ^ y >> 1 | |
if (z & 1 == 1): | |
self.mt[i] ^= 0x9908b0df | |
self.index = 0 | |
mt = MT19937(1) | |
for j in range(0, 624): | |
print mt.extract_number() >> 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment