Created
November 6, 2025 03:00
-
-
Save TwoSquirrels/4a505751dd4920b62a24b27dbbeda454 to your computer and use it in GitHub Desktop.
Python implementation of Mersenne Twister 19937 RNG without imports
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
| def mt19937ar_init(seed = 5489): | |
| """Given a seed, return a state of the MT19937 random number generator.""" | |
| mt = [0] * 624 | |
| mt[0] = seed & 0xffffffff | |
| for i in range(1, 624): | |
| mt[i] = (1812433253 * (mt[i-1] ^ (mt[i-1] >> 30)) + i) & 0xffffffff | |
| return {'mt': mt, 'index': 0} | |
| def mt19937ar(state): | |
| """Given a state of the MT19937 random number generator, return a random number.""" | |
| mt = state['mt'] | |
| if state['index'] == 0: | |
| for i in range(624): | |
| y = (mt[i] & 0x80000000) | (mt[(i+1) % 624] & 0x7fffffff) | |
| mt[i] = mt[(i + 397) % 624] ^ (y >> 1) | |
| if y % 2 != 0: | |
| mt[i] ^= 0x9908b0df | |
| y = mt[state['index']] | |
| y ^= y >> 11 | |
| y ^= (y << 7) & 0x9d2c5680 | |
| y ^= (y << 15) & 0xefc60000 | |
| y ^= y >> 18 | |
| state['index'] = (state['index'] + 1) % 624 | |
| return y | |
| ## Original C code from http://www.math.sci.hiroshima-u.ac.jp/m-mat/MT/MT2002/mt19937ar.html | |
| ## Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura, | |
| ## All rights reserved. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment