Skip to content

Instantly share code, notes, and snippets.

@amano41
Created October 24, 2018 13:26
Show Gist options
  • Save amano41/4d254198333d890e6ef7ba622923e87c to your computer and use it in GitHub Desktop.
Save amano41/4d254198333d890e6ef7ba622923e87c to your computer and use it in GitHub Desktop.
Xorshift and xorshift+ implementation in Python
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()
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