March 16th, 2013, 08:23 AM

Coding with probability
Hey, i am trying to write a function which will produce, u with probability p, or d with probability 1p:
so far i have:
import random
def choose_factor(u,d,p):
x=random.random()
if x<p:
return #missing piece of code
else:
return #missing piece of code
Could somebody give me a hand on what i should put in here, i have tried:
x=random.random()
if x<p:
return u
else:
return d
def main():
p=0.6
u=p
d=1p
j=choose_factor(u,d,p)
print (j)
pass
but im not sure if this is correct, thank you
March 16th, 2013, 02:05 PM

Sure, it's correct. But look, the values of u and d are entirely arbitrary. Anyway, you can verify your choice with a test:
Code:
import random
def choose_factor(u,d,p):
return u if random.random() < p else d
def main():
p = 0.6
u = 'U'
d = 'D'
return choose_factor(u,d,p)
def stats():
n = 1000
u = 0
for i in range(n):
u += 'U' == main()
print('expect 60%')
print('U: {}%'.format(int(round(100*u/float(n)))))
stats()
[code]
Code tags[/code] are essential for python code and Makefiles!
March 16th, 2013, 02:21 PM

Just a technical note on computer science and math:
As floating point numbers are not stored in the conventional binary sense, it might be more ideal to use integers (just multiply your values by 1000 or so) to get more accurate results.