Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import random
- # Step 1: Biased coin
- def rand01():
- return 1 if random.uniform(0, 1) > 0.8 else 0
- # Step 2: Convert to fair coin
- def fair_rand01():
- while True:
- a = rand01()
- b = rand01()
- if a == 0 and b == 1:
- return 0
- elif a == 1 and b == 0:
- return 1
- # Step 3: Directly generate 1 to 10
- def rand1to10():
- 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
- num = (
- fair_rand01() * 8 +
- fair_rand01() * 4 +
- fair_rand01() * 2 +
- fair_rand01()
- )
- if num < 10: # accept only 0–9
- return num + 1
- #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
- def rand4to10():
- while True:
- num = fair_rand01()*4 + fair_rand01()*2 + fair_rand01() # 0–7
- if num < 7:
- return num + 4
- # Test
- for _ in range(20):
- print(rand1to10())
Advertisement
Add Comment
Please, Sign In to add comment