简体   繁体   English

Python - 骰子和硬币游戏

[英]Python - dice and coin game

referring to 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?" “假设我掷了一个 4 面的骰子,然后根据掷骰子的次数掷出一个公平的硬币。鉴于我在掷硬币时得到三个正面,骰子得分为 4 的概率是多少?”

In the answer it is explained that the result should be 2/3.在答案中解释说结果应该是 2/3。

I wrote the following piece of code in Python 3:我在 Python 3 中编写了以下代码:

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)

I expect it to output something around 0.66, but it actually computes around 0.25.我预计它会输出大约 0.66 的值,但实际上它的计算值大约为 0.25。

Am I poorly understanding Python or Bayes' theorem?我对 Python 或贝叶斯定理的理解很差吗?

Your code is actually answering the question "Given the die score was a 4, what is the probability you got three heads on the coin flip?"您的代码实际上是在回答“鉴于骰子得分为 4,您在掷硬币时出现三个正面的概率是多少?”这个问题。 To make it answer the intended question, change the condition of your next-to-last if statement:要使其回答预期的问题,请更改倒数第二个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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM