1. No Profile Picture
Registered User
Devshed Newbie (0 - 499 posts)

Join Date
Feb 2013
Posts
2
Rep Power
0

#### Coding with probability

Hey, i am trying to write a function which will produce, u with probability p, or d with probability 1-p:

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=1-p
j=choose_factor(u,d,p)
print (j)
pass

but im not sure if this is correct, thank you
2. 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()```
3. No Profile Picture
Contributing User
Devshed Newbie (0 - 499 posts)

Join Date
Dec 2012
Posts
80
Rep Power
6
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.