Guest User

Untitled

a guest
Jul 16th, 2018
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.48 KB | None | 0 0
  1. import random
  2. import matplotlib.pyplot as plt
  3.  
  4. def rnd5():
  5. while True:
  6. yield random.randint(1,5)
  7.  
  8. # idea behind this:
  9. # fold sufficiently large (size affects precision)
  10. # string of base5 numbers to a [0.0, 1.0) range,
  11. # then unfold it into a base7 number and take its
  12. # integral part
  13. #
  14. # takes fixed point base5 number in an
  15. # array ordered most-significant digit first
  16. # (0 . b5[0] b5[1] ... b5[-1])
  17. # returns first digit after the point of base7 number
  18. def b5tob7d1(b5):
  19. fp = 0.0
  20. for d in b5:
  21. fp = fp * 5.0 + d
  22. fp /= pow(5, len(b5))
  23. return int(fp * 7)
  24.  
  25. def rnd7(rnd5, precision):
  26. source = [rnd5.next()-1 for i in range(precision)]
  27. while True:
  28. yield b5tob7d1(source)+1
  29. source.pop(0)
  30. source.append(rnd5.next()-1)
  31.  
  32.  
  33.  
  34. # visual 'proof'
  35.  
  36. r5 = rnd5()
  37. gens = [(r5, 5, ''),
  38. (rnd7(r5, 1), 7, ' d=1'),
  39. (rnd7(r5, 2), 7, ' d=2'),
  40. (rnd7(r5, 3), 7, ' d=3'),
  41. (rnd7(r5, 4), 7, ' d=4'),
  42. ]
  43.  
  44. def samples(gen):
  45. sample_sizes = [100, 1000, 10000]
  46. return [([gen.next() for i in range(s)], s) for s in sample_sizes]
  47.  
  48. samples = [(samples(g), r, t) for (g, r, t) in gens]
  49.  
  50. plt.interactive(True)
  51.  
  52. for i in range(len(samples)):
  53. ss, r, t = samples[i]
  54. for j in range(len(ss)):
  55. s, n = ss[j]
  56. plt.subplot(len(ss), len(samples), j*len(samples)+i+1)
  57. plt.hist(s, range(1,r+2), normed=True)
  58. plt.title('1..%d %s n=%d'%(r, t, n))
  59.  
  60. plt.subplots_adjust(hspace=0.3, wspace=0.4)
  61. plt.draw()
  62. plt.waitforbuttonpress()
Add Comment
Please, Sign In to add comment