imashutosh51

generate 1to7 using a unfair 0/1 function

Apr 16th, 2026
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.41 KB | None | 0 0
  1. #From a unfair 0/1 function to generating random numbers from 1 to 7.
  2. '''
  3. rand01 is an unfair function and probability of getting 1 from rand01 is 80% where probability of getting 0 is only 20%.
  4. We are gonna make this function fair first, suppose we call that function 2 times then all the possibilities are:
  5. 00: probability of 0 and 0 is 0.2*0.2
  6. 01: probability of 0 and 1 is 0.2*0.8
  7. 10: probability of 1 and 0 is 0.8*0.2
  8. 11: probability of 1 and 1 is 0.8*0.8
  9.  
  10. 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.
  11.  
  12. Now You have to print numbers 1 to 7 randomly and random numbers have the same probability for all the numbers.
  13. 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.
  14.  
  15. 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.
  16. '''
  17. import random
  18. def rand01():
  19.     return 1 if random.uniform(0,1)>=0.8 else 0
  20.  
  21. def fair_rand01(): #it only returns either 0 or 1.
  22.     while True:
  23.         a,b=rand01(),rand01()
  24.         if (a==0 and b==1):
  25.             return 0
  26.         elif a==1 and b==0:
  27.             return 1
  28.  
  29. def rand1to7():
  30.     while True:
  31.         a,b,c=fair_rand01(),fair_rand01(),fair_rand01()
  32.         num=fair_rand01()*4 + fair_rand01()*2+ fair_rand01()
  33.         if num!=0:
  34.             return num
  35. k=20
  36. while k>=0:
  37.     print(rand1to7())
  38.     k-=1
Advertisement
Add Comment
Please, Sign In to add comment