-
-
Save DuckyShine004/02642f53ead5bc411a30300071cd8725 to your computer and use it in GitHub Desktop.
Xorshift and xorshift+ implementation in Python
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 xorshift128(): | |
'''xorshift | |
https://ja.wikipedia.org/wiki/Xorshift | |
''' | |
x = 123456789 | |
y = 362436069 | |
z = 521288629 | |
w = 88675123 | |
def _random(): | |
nonlocal x, y, z, w | |
t = x ^ ((x << 11) & 0xFFFFFFFF) # 32bit | |
x, y, z = y, z, w | |
w = (w ^ (w >> 19)) ^ (t ^ (t >> 8)) | |
return w | |
return _random | |
def main(): | |
r = xorshift128() | |
for i in range(10): | |
print(r()) | |
if __name__ == '__main__': | |
main() |
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 xorshift32(): | |
"""https://en.wikipedia.org/wiki/Xorshift""" | |
state = 1804289383 # Override with your initial state | |
def _random(): | |
nonlocal state | |
next_state = state | |
next_state ^= (next_state << 13) & 0xFFFFFFFF | |
next_state ^= (next_state >> 17) | |
next_state ^= (next_state << 5) & 0xFFFFFFFF | |
state = next_state | |
return state | |
return _random | |
def main(): | |
r = xorshift32() | |
for _ in range(10): | |
print(r()) | |
if __name__ == "__main__": | |
main() |
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 xorshift128plus(): | |
'''xorshift+ | |
https://en.wikipedia.org/wiki/Xorshift#xorshift+ | |
シフト演算で使用している 3 つの数値は元論文 Table.1 参照 | |
http://vigna.di.unimi.it/ftp/papers/xorshiftplus.pdf | |
doi:10.1016/j.cam.2016.11.006 | |
''' | |
s0 = 1 | |
s1 = 2 | |
def _random(): | |
nonlocal s0, s1 | |
x, y = s0, s1 | |
x = x ^ ((x << 23) & 0xFFFFFFFFFFFFFFFF) # 64bit | |
x = (x ^ (x >> 17)) ^ (y ^ (y >> 26)) | |
s0, s1 = y, x | |
return s0 + s1 | |
return _random | |
def main(): | |
r = xorshift128plus() | |
for i in range(10): | |
print(r()) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment