Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #From a unfair 0/1 function to generating random numbers from 1 to 7.
- '''
- rand01 is an unfair function and probability of getting 1 from rand01 is 80% where probability of getting 0 is only 20%.
- We are gonna make this function fair first, suppose we call that function 2 times then all the possibilities are:
- 00: probability of 0 and 0 is 0.2*0.2
- 01: probability of 0 and 1 is 0.2*0.8
- 10: probability of 1 and 0 is 0.8*0.2
- 11: probability of 1 and 1 is 0.8*0.8
- One thing to notice here that probability of 01 and 10 is same so I made a new function fair_rand01() which returns 0 and 1 fairly with equal chances.so I will keep calling the unfair function for two times, if I will get 01 I will return 0 and if I will get 10 then I will return 1 and I am not considering any other possibility so now that function returns either 0 or 1 and both are having the same probability so probability of getting either 0 or 1 from fair_rand01 function is 50% each.
- Now You have to print numbers 1 to 7 randomly and random numbers have the same probability for all the numbers.
- Now I will call the fair_rand01 function 3 times and the outputs can be: 000,001,010,100,011,101,110,111 so consider them as bits so all the bits in decimal becomes: 0,1,2,3,4,5,6,7 so now comes the rand1to7() function.
- I will keep calling the fair_rand01() which gives fairly 0 and 1 for 3 times, so all numbers from 0 to 7 have same probability so technically all the numbers from 1 to 7 have also the same probability.I will discard the 000 values ie. 0 and consider only the 1 to 7, Now if you will see fair_rand01() will return only the numbers from 1 to 7 and internally of this function probability of 0 to 8 coming is 1/8 for all the numbers which is same for everyone and now If you see the fuction from outside, it only returns 1->7 only with same probability so from outside, coming probability of coming any number from 1 to 7 is 1/7.
- '''
- import random
- def rand01():
- return 1 if random.uniform(0,1)>=0.8 else 0
- def fair_rand01(): #it only returns either 0 or 1.
- while True:
- a,b=rand01(),rand01()
- if (a==0 and b==1):
- return 0
- elif a==1 and b==0:
- return 1
- def rand1to7():
- while True:
- a,b,c=fair_rand01(),fair_rand01(),fair_rand01()
- num=fair_rand01()*4 + fair_rand01()*2+ fair_rand01()
- if num!=0:
- return num
- k=20
- while k>=0:
- print(rand1to7())
- k-=1
Advertisement
Add Comment
Please, Sign In to add comment