Reputation: 1021
I am working through the MIT OpenCourseWare intro to computer programming course and I am not sure if I am solving a simple simulation the right way.
- What is the probability of rolling a Yahtzee! on the first roll? That is, what is the probability of rolling five 6-sided dice, and having them all display the same number?
- Write a Monte Carlo simulation to solve the above problem (the Yahtzee problem), and submit your code as
So the probability of rolling a Yahtzee is 1/1296 or about .077%
Here is my code to run the simulation:
import random
def runYahtzee(numTrials):
"""Runs the classes version of the yahtzee simulation"""
success = 0
for i in range(numTrials):
dices = []
for i in range(6):
dices.append(random.randrange(1,7))
#print dices
state = True
for dice in dices:
if dice != dices[0]:
state = False
if state == True:
print "You got a Yahtzee"
print dices
success += 1
print "numTrials is: " + str(numTrials)
print "Success is: " + str(success)
rate = float(success)/numTrials
return rate
runYahtzee(10000000)
Running the program multiple times, I get around .0001258 each time. This is .012%, but the actual probability is around .077%. Is there something that I am doing wrong here?
Upvotes: 1
Views: 856
Reputation: 56684
Here's how I'd write it (Python 3):
from collections import Counter
from random import randint
def roll():
return randint(1, 6)
def is_yahtzee(num_dice = 5):
first = roll()
return all(roll() == first for _ in range(1, num_dice))
def montecarlo(fn, num_trials):
return Counter(fn() for _ in range(num_trials))
def main():
num_trials = 10000000
result = montecarlo(is_yahtzee, num_trials)
prob = result[True] / num_trials
print(
"After {} trials, probability of Yahtzee is {:0.5f}%"
.format(num_trials, 100. * prob)
)
if __name__ == "__main__":
main()
which runs like
After 10000000 trials, probability of Yahtzee is 0.07605%
Note that keeping your functions short generally makes them easier to understand and test.
Upvotes: 0
Reputation: 77860
What you're doing wrong is rolling 6 dice instead of 5.
0.001258 * 6 = 0.0007548
... which is close to your 0.077%
Change your loop:
for i in range(5):
BTW, the plural is dice
; the singular is die
. dices
is wrong, unless you're trying to be amusing. In that case, you can use the singular "douse" ... never say die!
Upvotes: 5