Random generator from 1-7 from a given random generator 1-5

INPUT: import random def rand5(): return random.randint(1, 5) def rand7(): """ Generating 25 random numbers uniformly between 1-25 and picking up modulo 7 from first 21 of them 1 2 3 4 5 6 7 1 2 3 4 5 6 7 1 2 3 4 5 6 7 - - - - """ while True: # x is uniformly generated between 1-25 x = 5 * (rand5() - 1) + rand5() if (x <= 21): # Ignore >21 numbers break # Result is now uniformly random between 1-7 return x % 7 + 1 def distribution(foo): d = {} for _ in xrange(10000): x = foo() if x not in d: d[x] = 0 d[x] += 1 return d print distribution(rand7) print distribution(rand5) OUTPUT: {1: 1446, 2: 1422, 3: 1417, 4: 1442, 5: 1459, 6: 1403, 7: 1411} {1: 1995, 2: 2016, 3: 1999, 4: 1992, 5: 1998}

Comments

Popular posts from this blog

Multiple repeat error when the regex has multiple wildcards in python re module

Weakref proxy is for instance only ...

To speed up accessing files on nfs shares on a ubuntu machine ...