Want more features on Pastebin? Sign Up, it's FREE!
Guest

rng

By: phillip1882 on Jun 22nd, 2012  |  syntax: Python  |  size: 1.16 KB  |  views: 56  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. v = [0]*3
  2. seed1 = 1987325923
  3. v[0] = 0x96696996
  4. v[1] = seed1
  5. v[2] = 0xb5b5adad
  6. def rot(x,k):
  7.    return ((x<<k)|(x>>(32-k)))&4294967295
  8.    #the &num is unnecessary in other programing languages
  9.  
  10. def rng():
  11.    v[0], v[2], v[1] = rot(v[2],8), rot(v[1],17), v[0]^(~v[1]&v[2])
  12.    return v[1]
  13.  
  14. #some randomness tests
  15. def bucket(iter):
  16.    size = int(iter/2.71828)
  17.    array = [0]*size
  18.    for i in range(0,iter):
  19.       array[rng()%size] += 1
  20.    count = 0
  21.    for i in range(0,size):
  22.       if array[i] > 7 or array[i] == 0:
  23.          count += 1
  24.    if count < size/2.718:
  25.       print("pass")
  26.    else:
  27.       print("fail",count)
  28.  
  29. def pi_aprox(iter):
  30.    hits = 0
  31.    for i in range(0,iter):
  32.       x = (rng()&8388607)/(8388608.0)
  33.       y = (rng()&8388607)/(8388608.0)
  34.       pos = x*x+y*y
  35.       if pos < 1.0:
  36.          hits += 1
  37.    hits = hits*4.0/iter
  38.    print(hits)
  39.  
  40. def arithmean(iter):
  41.    total = 0.0
  42.    for i in range(0,iter):
  43.       val = rng()
  44.       a = (val&4278190080)>>24
  45.       b = (val&16711680)>>16
  46.       c = (val&65280)>>8
  47.       d = val&255
  48.       total += (a+b+c+d)/4
  49.    print(127.5-total/iter)
  50.  
  51.  
  52. bucket(10000)
  53. arithmean(10000)
  54. pi_aprox(10000)
clone this paste RAW Paste Data