我是 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_flip
次,数正面和反面,看看正面是否多于反面。如果是,将 head_rounds_won
加 1。重复 10000 次。
我假设 head_rounds_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
会返回类似的东西
>>> FlipCoins(2)
(2506, 2503, 4991)
关于Python 抛硬币,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11380350/