I’m trying to simulate a continuous randomly generated number distribution in Python and find the combined numbers (where y=x1+x2) fall within p(0.9
n = 10000
x11 = [random.random() for i in range(n)]
x12 = [random.random() for i in range(n)]
x21 = [-0.5*(log(1-random.random())) for i in range(n)]
x22 = [-0.5*(log(1-random.random())) for i in range(n)]
x31 = [random.random() for i in range(n)]
x32 = [random.uniform(0,2) for i in range(n)]
x41 = [0.25 if random.random() < 0.8 else 1.5 for r in range(n)]
x42 = [0.25 if random.random() < 0.8 else 1.5 for r in range(n)]
x11 through x42 are pairs of cases that I’m trying to get the probability that they’ll fall between 0.9 and 1.8 where the pairs of lists generated are combined and then operated on. So x11 and x12 are combined and then expected value, variance, and the 0.9 to 1.8 p(x) is found.
def test():
x1,x2,c = 0.0,0.0,0.0
for i in range(10000):
if random.random()< 0.8:
x1 += 0.25
else:
x2 += 1.5
y = x1 + x2
if y>0.9 and y<=1.8:
c = c + 1
return x1,x2,c
print "test: ",test()
def sim(a,b):
#pyab1 = sum([a for a in a if a>0.9 and a<=1.8])/10000
#pyab2 = sum([b for b in b if b>0.9 and b<=1.8])/10000
#print "*****",float(pyab1+pyab2)
#print a+b
#array1 = [[a],[b]]
array1 = a+b
#array1.extend(a)
#array1.extend(b)
#c = 0
#for y in array1:
#if y>0.9 and y<=1.8:
#c = c + 1
pyab = sum([y for y in array1 if y>0.9 and y<=1.8])/10000
print("P(a < x <= b) : {0:8.4f}".format(pyab))
I’m only counting the probability P(0.9<%Y<=1.8) so the count has to fall within those values. The 1-random.random() was only for that case, when I tried using that for all the cases they still came up with the wrong values. Here’s the theoretical outcomes and you can see how it’s different:
y~u(0,1)
= 0.575y~exp(2)
= 0.3371x1~u(0,1)
x2~u(0,2)P(y=0.25)=0.8
P(y=1.5)=0.2
= 0.2
Here’s the output followed by the values it’s supposed to give, but this shows how far off the results are.
case 1: P(a < x <= b) : 0.7169 #should be 0.575
case 2: P(a < x <= b) : 0.4282 #should be 0.3371
case 3: P(a < x <= b) : 0.5966 #should be 0.4413
case 4: P(a < x <= b) : 0.5595 #should be 0.2
I’m very new to Python so please be patient if my question seems to have an obvious solution that I missed.
most probably you’d better replace
with
since you need the probabilities, but not the sum of the actual values. also, the
len(array1)most probably is not 10000, but the combined length of two arrays.