jeudi 18 avril 2019

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?




Aucun commentaire:

Enregistrer un commentaire