How to make a fair coin from a biased coin using a program in Python
Problem Explanation
Suppose there is a function named unFairCoin()
that represents a biased coin. When this function is called then it will return 0 with 70% probability and return 1 with 30% probability. By using this function only we have to make a fair coin that will return 0 or 1 with 50% probability each.
Code With Explanation
import random def unFairCoin(): if random.random() < 0.3: return 1 else: return 0 def FairCoin(): coin1 = unFairCoin(); coin2 = unFairCoin(); print(coin1,coin2) if coin1 == 0 and coin2 == 1: return 0 if coin1 == 1 and coin2 == 0: return 1 return FairCoin() print(FairCoin())
The unFairCoin() function will return 1 with 30% probability and returns 0 with 70% probability. We can say that unFairCoin()
is a biased function like a biased coin. We have to use this function to make a new function named as FairCoin()
which will return 0 or return 1 with 50% probability.
In the above code if we toss the coin twice i.e if the unFairCoin() function is called twice and store in coin1 and coin2.Both coins will return 0 with a 70% probability.
If both the coin1 and coin2 will have a value 0 then the probability of getting both zero is (0.7*0.7 = 0.49) and if both coin1 and coin2 will have a value 1 then the probability of getting that is (0.3*0.3 = 0.09). Now if there is a case where coin1 is getting 0 and coin2 is getting 1 then for that probability will be (0.7*0.3 = 0.21) and similarly if coin1 is getting 1 and coin2 is getting 0 then for that the probability will be (0.3*0.7 = 0.21).
Now we see the probability of (coin1=0 and coin2=1) is the same as (coin1=1 and coin2=0) which is equal to 0.21. So from here, we can determine that if both the coin have different value then one of the two cases of coin1 and coin2 will return 0 and the other case will return 1.
Here in the above code, we have chosen (coin1==0 and coin2==1) to return 0 and (coin1==1 and coin2==0) to return 1 and if both the coins are equal then we will recur(i.e, the function will call itself) until both the coin have a different value.
Leave a Reply