Python - 骰子和投币游戏

Python - dice and coin game

参考this question:

"Suppose I roll a 4-sided die, then flip a fair coin a number of times corresponding to the die roll. Given that i got three heads on the coin flip, what is the probability the die score was a 4?"

答案中说明结果应该是2/3。

我在Python3写了下面这段代码:

import random

die=4
heads=3

die_max=4

tot=0
tot_die=0
for i in range(0,100000) :
    die_val=random.randint(1,die_max)
    heads_val=0
    for j in range(0,die_val) :
        heads_val+=random.randint(0,1)
    if die_val==die :
        tot_die+=1
    if heads_val==heads and die_val==die :
        tot+=1
print(tot/tot_die)

我预计它会输出 0.66 左右的值,但实际上计算结果约为 0.25。

我是不是对 Python 或贝叶斯定理理解得不好?

您的代码实际上是在回答问题 "Given the die score was a 4, what is the probability you got three heads on the coin flip?" 要使其回答预期的问题,请更改倒数第二个 if 语句的条件:

import random

die=4
heads=3

die_max=4

tot=0
tot_heads=0
for i in range(0,100000) :
    die_val=random.randint(1,die_max)
    heads_val=0
    for j in range(0,die_val) :
        heads_val+=random.randint(0,1)
    if heads_val==heads : # the important change
        tot_heads+=1
    if heads_val==heads and die_val==die :
        tot+=1
print(tot/tot_heads)