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