Python 巨蟒抛硬币

Python 巨蟒抛硬币,python,random,Python,Random,我对Python还不熟悉,我无法理解这一点。我定义了以下函数: def FlipCoins(num_flips): heads_rounds_won = 0 for i in range(10000): heads = 0 tails = 0 for j in range(num_flips): dice = random.randint(0,1) if dice==1: heads

我对Python还不熟悉,我无法理解这一点。我定义了以下函数:

def FlipCoins(num_flips):
    heads_rounds_won = 0
    for i in range(10000):
        heads = 0
        tails = 0
        for j in range(num_flips):
            dice = random.randint(0,1)
            if dice==1: heads += 1
            else: tails += 1
        if heads > tails: heads_rounds_won += 1
    return heads_rounds_won
下面是它应该做的(但显然不是):掷硬币
num\u flip
次,计算正面和反面,看看正面是否多于反面。如果是,则将
head\u rounds\u won
增加1。重复10000次

我认为,
head\u rounds\u won
大约为5000(50%)。对于奇数作为输入,它会这样做。例如,3、5或7将产生约50%。然而,即使是偶数也会产生更低的结果,更像34%。特别是小数字,偶数更高,例如800,与50%的差异要小得多


为什么会这样?难道任何输入都不应该产生大约50%的正面/反面吗?

你只是得到了很多平局的回合

def FlipCoins(num_flips):
    heads_rounds_won = 0
    tails_rounds_won = 0
    tied_rounds = 0
    for i in range(10000):
        heads = 0
        tails = 0
        for j in range(num_flips):
            dice = random.randint(0,1)
            if dice==1: heads += 1
            else: tails += 1
        if heads > tails: heads_rounds_won += 1
        elif heads < tails: tails_rounds_won+= 1
        else: tied_rounds += 1
    return heads_rounds_won, tails_rounds_won, tied_rounds
这很有趣,并且(最终)证明了randint(0,1)选择0或1的概率为50/50。社区维基,因为它的信息丰富,但不是对这个问题的直接回答

s = [0, 0]
while True:
    an_int = randint(0, 1)
    s[an_int] += 1
    l = sum(s)
    print 'size: %d - %f%% zeros, %f%% ones' % (l, (100 * s[0]) / float(l), (100 * s[1]) / float(l))

对于奇数,正面>反面或反面>正面,但对于偶数,有3种情况:正面>反面,反面>正面&正面==反面。如果正面=反面,你会怎么做?我希望随着翻转次数的增加,这种情况会减少。这能解释你的问题吗?@user1245262:(+1)。这真是个好主意Auser1245262:是的,你说得对,我没有考虑领带。我仍然不明白为什么奇数和偶数作为输入会有如此不同的结果。例如,使用下面Mitch答案中的代码,input 100始终生成8%左右的平局(这不可能是正确的),而input 99几乎从不出现平局但是8%的领带和你期望的差不多。Pr[50正面和50反面]=100选择50*(0.5)^50*(0.5)^50=0.079589。。。。(我是用math.factorial(100)/(math.factorial(50)*math.factorial(50))*math.pow(2,-100)来做的。我想用numpy或scipy会有一个更平滑的方法来做这件事,但我没有很快找到它。用户:谢谢,我想这是有道理的——直觉上我会认为8%太多了
s = [0, 0]
while True:
    an_int = randint(0, 1)
    s[an_int] += 1
    l = sum(s)
    print 'size: %d - %f%% zeros, %f%% ones' % (l, (100 * s[0]) / float(l), (100 * s[1]) / float(l))