imashutosh51

random numbers generation using unfair coin in any range

Apr 16th, 2026
51
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.07 KB | None | 0 0
  1. import random
  2.  
  3. # Step 1: Biased coin
  4. def rand01():
  5.     return 1 if random.uniform(0, 1) > 0.8 else 0
  6.  
  7. # Step 2: Convert to fair coin
  8. def fair_rand01():
  9.     while True:
  10.         a = rand01()
  11.         b = rand01()
  12.         if a == 0 and b == 1:
  13.             return 0
  14.         elif a == 1 and b == 0:
  15.             return 1
  16.  
  17. # Step 3: Directly generate 1 to 10
  18. def rand1to10():
  19.     while True: #here range is 1 to 10 means 10 number so look for smallest value of 2 which make it either 10 or more ie 2^4
  20.         num = (
  21.             fair_rand01() * 8 +
  22.             fair_rand01() * 4 +
  23.             fair_rand01() * 2 +
  24.             fair_rand01()
  25.         )
  26.        
  27.         if num < 10:   # accept only 0–9
  28.             return num + 1
  29. #Another example when the numbers to generate are 4 to 10 where the range is 7 number and 2^3=8 which is just above 7
  30. def rand4to10():
  31.     while True:
  32.         num = fair_rand01()*4 + fair_rand01()*2 + fair_rand01()  # 0–7
  33.         if num < 7:
  34.             return num + 4            
  35.  
  36. # Test
  37. for _ in range(20):
  38.     print(rand1to10())
Advertisement
Add Comment
Please, Sign In to add comment