简体   繁体   中英

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?"

In the answer it is explained that the result should be 2/3.

I wrote the following piece of code in 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.

Am I poorly understanding Python or Bayes' theorem?

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?" To make it answer the intended question, change the condition of your next-to-last if statement:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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