简单的 Yahtzee 模拟没有给出正确的结果?

Simple Yahtzee simulation not giving proper result?

我正在学习 MIT OpenCourseWare 计算机编程入门课程,我不确定我是否以正确的方式解决了一个简单的模拟问题。

  1. 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?
  2. Write a Monte Carlo simulation to solve the above problem (the Yahtzee problem), and submit your code as

所以滚动 Yahtzee 的概率是 1/1296 或大约 .077%

这是我的 运行 模拟代码:

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)

运行 程序多次,我每次都在 .0001258 左右。这是 0.012%,但实际概率约为 0.077%。我在这里做错了什么吗?

你做错的是掷 6 个骰子而不是 5 个。

0.001258 * 6 = 0.0007548

...接近您的 0.077%

改变你的循环:

    for i in range(5):

顺便说一句,复数是dice;单数是 diedices 错误的 ,除非你想变得有趣。在这种情况下,您可以使用单数 "douse" ... never say die!

我会这样写 (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()

运行起来像

After 10000000 trials, probability of Yahtzee is 0.07605%

请注意,保持函数简短通常会使它们更易于理解和测试。