Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
#MonthOfCode day 17 - random
import time
current_milli_time = lambda: int(round(time.time() * 1000))
# we use the Factory Design Pattern, RngCreator is the abstract class
class RngCreator(object):
def createRng(self):
raise NotImplementedError("Please Implement this method")
def inputParams(self, p_dict):
raise NotImplementedError("Please Implement this method")
class LcgCreator(RngCreator):
#default values
prod_a, prod_c, prod_m = 22695477,1, 2**32 #parameters used by the Borland C/C++ compiler
def createRng(self):
return Lcg(self.prod_a, self.prod_c, self.prod_m)
def inputParams(self, p_dict):
self.prod_a, self.prod_c, self.prod_m = p_dict['a'], p_dict['c'],p_dict['m']
class Lcg:
'''A linear congruential generator (LCG) is an algorithm that yields
a sequence of randomized numbers calculated with a linear equation.'''
seed = current_milli_time()
prev_val = seed
def __init__(self, a, c, m):
self.a, self.c, self.m = a,c,m
def randomRaw( self):
self.prev_val = (
self.a * self.prev_val + self.c) % self.m #formula for generating a new pseudo-rand number
return self.prev_val
def randint( self, binf, bsup):
if( bsup<= binf):
raise ValueError("bsup must be greater than binf")
random_var = self.randomRaw()
return binf +( random_var % (bsup-binf+1) )
def performTestRng( generator ):
''' simulates numerous dice throws! '''
NB_THROWS = 6* 100
occurences = [ 0 for i in xrange(6) ]
for n in xrange( NB_THROWS ):
nb = generator.randint(1,6)
print nb,
for i in range(1,7):
if(i == nb):
print ;
for i in range(1,7):
print "nb",i,"occurs",occurences[i-1]," ;",
print ;
generator1 = LcgCreator().createRng()
print "testing the first RNG:" ; performTestRng( generator1)
custom_creator = LcgCreator()
{'a':25214903917, 'c':11, 'm':2**48 } ) # parameters used by Java.util.Random
generator2 =custom_creator.createRng()
print "testing the second RNG:" ; performTestRng( generator2)

This comment has been minimized.

Show comment Hide comment

floriancargoet Mar 22, 2014



Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment