在Python 2.7中将不公平的硬币转换成公平的硬币

时间:2016-10-13 05:38:30

标签: python algorithm python-2.7 probability coin-flipping

使用Python 2.7。假设我有一个不公平的硬币,我想用下面的方式把它变成一个公平的硬币,

  1. 对于不公平的硬币,生成头的概率是相等的;
  2. 翻转不公平的硬币,只接受头;
  3. 当头部出现时,将其视为1(虚拟公平硬​​币的头部),当另一个头部出现时,将其视为0(虚拟公平硬​​币的尾部),下次出现头部时,将其视为1,下次将其视为0,......等等。
  4. 不确定此方法是否有效?实际上我对上面的方法以及如何正确使用equalCoinHelper()并不是很有信心(我在我的代码中标记了我的问题)。

    如果有人有任何好的想法,那就太好了。

    from __future__ import print_function
    import random
    counter = 0
    
    # 0.3 probability return head as 1
    # 0.7 probability return tail as 0
    def unFairCoin():
       if random.random() < 0.3:
           return 1
       else:
           return 0
    
    # probability of generating 1 is equal, so keep 1 only
    def equalCoinHelper():
        result = 0
        while result == 0:
            result = unFairCoin()
    
    def equalDistribution():
        global counter
        # not think about how to leverage this better
        equalCoinHelper()
        counter += 1
        if counter % 2 == 0:
            return 1
        else:
            return 0
    
    if __name__ == "__main__":
        # generate 10 random 0/1 with equal probability
        print ([equalDistribution() for _ in range(10)])
    

2 个答案:

答案 0 :(得分:3)

Getting a Fair Toss From a Biased Coin解释了一种将有偏见的硬币变成公平硬币的简单算法:

  1. 翻转硬币两次。
  2. 如果两个投掷相同(头部或尾部 - 尾部),请重复步骤1.
  3. 如果掷骰子出现在尾巴上,那就把它折腾为头。如果扔掉了尾巴,可以算作尾巴。
  4. 在Python中,这将是:

    def fairCoin():
        coin1 = unfairCoin()
        coin2 = unfairCoin()
        if coin1 == coin2:
            return fairCoin() # both are the same, so repeat it
        elif coin1 == 1 and coin2 == 0:
            return 1
        else:
            return 0
    

    elifelse块可以简化为:

        else:
            return coin1
    

答案 1 :(得分:2)

@ Barmar的答案的另一种实现方式,即避免递归调用(即使它可能是无害的)

def fairCoin():
    coin1 = 0
    coin2 = 0
    while coin1 == coin2:
        coin1 = unfairCoin()
        coin2 = unfairCoin()
    return coin1