Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import random
- import matplotlib.pyplot as plt
- def rnd5():
- while True:
- yield random.randint(1,5)
- # idea behind this:
- # fold sufficiently large (size affects precision)
- # string of base5 numbers to a [0.0, 1.0) range,
- # then unfold it into a base7 number and take its
- # integral part
- #
- # takes fixed point base5 number in an
- # array ordered most-significant digit first
- # (0 . b5[0] b5[1] ... b5[-1])
- # returns first digit after the point of base7 number
- def b5tob7d1(b5):
- fp = 0.0
- for d in b5:
- fp = fp * 5.0 + d
- fp /= pow(5, len(b5))
- return int(fp * 7)
- def rnd7(rnd5, precision):
- source = [rnd5.next()-1 for i in range(precision)]
- while True:
- yield b5tob7d1(source)+1
- source.pop(0)
- source.append(rnd5.next()-1)
- # visual 'proof'
- r5 = rnd5()
- gens = [(r5, 5, ''),
- (rnd7(r5, 1), 7, ' d=1'),
- (rnd7(r5, 2), 7, ' d=2'),
- (rnd7(r5, 3), 7, ' d=3'),
- (rnd7(r5, 4), 7, ' d=4'),
- ]
- def samples(gen):
- sample_sizes = [100, 1000, 10000]
- return [([gen.next() for i in range(s)], s) for s in sample_sizes]
- samples = [(samples(g), r, t) for (g, r, t) in gens]
- plt.interactive(True)
- for i in range(len(samples)):
- ss, r, t = samples[i]
- for j in range(len(ss)):
- s, n = ss[j]
- plt.subplot(len(ss), len(samples), j*len(samples)+i+1)
- plt.hist(s, range(1,r+2), normed=True)
- plt.title('1..%d %s n=%d'%(r, t, n))
- plt.subplots_adjust(hspace=0.3, wspace=0.4)
- plt.draw()
- plt.waitforbuttonpress()
Add Comment
Please, Sign In to add comment