Advertisement
NLinker

XorShift+, the fast and good RNG

May 27th, 2019
273
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.92 KB | None | 0 0
  1. def xorshift128():
  2.     '''xorshift
  3.    https://ja.wikipedia.org/wiki/Xorshift
  4.    '''
  5.     x = 123456789
  6.     y = 362436069
  7.     z = 521288629
  8.     w = 88675123
  9.     def _random():
  10.         nonlocal x, y, z, w
  11.         t = x ^ ((x << 11) & 0xFFFFFFFF)  # 32bit
  12.         x, y, z = y, z, w
  13.         w = (w ^ (w >> 19)) ^ (t ^ (t >> 8))
  14.         return w
  15.     return _random
  16.  
  17.  
  18. def xorshift128plus():
  19.     '''xorshift+
  20.    https://en.wikipedia.org/wiki/Xorshift#xorshift+
  21.    http://vigna.di.unimi.it/ftp/papers/xorshiftplus.pdf
  22.    '''
  23.     s0 = 1
  24.     s1 = 2
  25.     def _random():
  26.         nonlocal s0, s1
  27.         x, y = s0, s1
  28.         x = x ^ ((x << 23) & 0xFFFFFFFFFFFFFFFF)  # 64bit
  29.         x = (x ^ (x >> 17)) ^ (y ^ (y >> 26))
  30.         s0, s1 = y, x
  31.         return s0 + s1
  32.     return _random
  33.  
  34.  
  35. def main():
  36.     r = xorshift128plus()
  37.     for i in range(10):
  38.         print(r())
  39.  
  40. if __name__ == '__main__':
  41.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement