In [5]:
%matplotlib inline
import matplotlib.pyplot as plt
import time
import math
def random(n):
lastXn = int(time.clock())+7897857
a = lastXn*8
b = a + 98756465
m = 900217+int(time.clock())
rList = []
for i in range(n):
Xn = float((a*lastXn + b)% m)
lastXn = Xn
random = float(Xn/m)
rList.append(random)
return rList
def genVAD(n, x, px):
dAcum = distAcum (x,px)
rList = random(n)
xList = []
for i in rList:
for j in range(len(dAcum)):
if(i <= dAcum[j]):
xList.append(x[j])
break
print "Generated numbers: "
print xList
plt.hist(xList)
def distAcum(x, px):
Px = []
suma = 0
for i in range(len(x)):
Px.append(suma + px[i])
suma = suma + px[i]
return Px
def genBernoulli(p):
# p = success probability
x = [0,1]
px = [(1-p),p]
return x,px
def genBinomial(ni,p):
# ni = number of attempts
# p = success probability for each attempt
x = []
px = []
for i in range(ni):
x.append(i)
for i in range(ni):
pi = (math.factorial(ni)/(math.factorial(x[i])*math.factorial(ni-x[i])))*(p**x[i])*((1-p)**(ni-x[i]))
px.append(pi)
print px
return x,px
def genHiperGeometrica(N, nm, d):
# N = Total number of the population
# n = Size of the extracted sample
# d = Number of elements in N that belong to the class we are looking for.
# x = Number of elements in n that belong to d
x = []
px = []
c = 0
while(c<=d):
x.append(c)
c = c+1
for i in x:
if(i>nm):
pi = 0
else:
pi = (float(math.factorial(d)/(math.factorial(i)*math.factorial(d-i)))*float(math.factorial(N-d)
/(math.factorial(nm-i)*math.factorial(N-d-nm+i))))/float(math.factorial(N)
/(math.factorial(nm)*math.factorial(N-nm)))
px.append(pi)
return x,px
def main():
#Distribucion de Bernoulli
'''
p = float(raw_input('Please input the p value: ')) #p value should be between 0 and 1
x, px = genBernoulli(p)
n = int(raw_input('Please input the amount of random numbers to generate: '))
genVAD(n,x,px)
'''
#Distribucion Binomial
'''
p = float(raw_input('Please input the p value: ')) #p value should be between 0 and 1
ni = int(raw_input('Please input the n value: '))
x, px = genBinomial(ni,p)
n = int(raw_input('Please input the amount of random numbers to generate: '))
genVAD(n,x,px)
'''
#Distrubcion Hipergeometrica
N = int(raw_input('Input the total number of population elements N:'))
nm = int(raw_input('Input the number of sample elements: '))
d = int(raw_input('Input the number of elements that belong to the wanted class: '))
x, px = genHiperGeometrica(N, nm, d)
n = int(raw_input('Please input the amount of random numbers to generate: '))
genVAD(n,x,px)
main()
In [ ]: