RandInt.py Program

From GM-RKB
(Redirected from RandInt.py)
Jump to navigation Jump to search

A RandInt.py Program is a Python-based random integer generator based solely on a Bernoulli process.



References

##############################################
# randInt.py (v1.0) - create a random integer generator given an unbiased coin.

import random
import math 

def randPower2 (n):
  num=0
  i=0
  while i <math.sqrt(n):
     coin=random.randint(0,1)
     if coin==1:
        num += 2**i
     i += 1
     #print "coin=", coin, "num=", num, "max=", (n-1)**2
  return num

# iterate through a power2 based random num generator
def randInt (n):
  randNum=n+1
  while randNum>n-1:
    randNum = randPower2(n) ;
    #print "randnum=",randNum

  return randNum

n=5
m=1000
L=[0]*n # initialize

while m>0:
  r=randInt(n)
  L[r]+=1 ;
  #print r
  m-=1

print "\n", L

# sample output
# [180, 201, 194, 210, 215]