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

时间:2017-06-06 23:16:47

标签: python python-2.7 simulation montecarlo

我正在通过麻省理工学院开放式课程介绍计算机编程课程,我不确定我是否正确地解决了简单的模拟。

  
      
  1. Yahtzee的滚动概率是多少!在第一卷?那就是什么   滚动五个6面骰子的概率,并让它们都显示相同的数字?
  2.   
  3. 写一个蒙特卡罗模拟来解决上述问题(Yahtzee问题),和   提交您的代码
  4.   

所以滚动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。这是.012%,但实际概率约为0.077%。我在这里做错了吗?

2 个答案:

答案 0 :(得分:5)

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

0.001258 * 6 = 0.0007548

...接近你的0.077%

更改循环:

    for i in range(5):
BTW,复数是dice;单数是diedices 错误,除非你试图有趣。在这种情况下,你可以使用单数" douse" ...... 从不说死!

答案 1 :(得分:0)

这是我写它的方式(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%

请注意,保持您的功能简短通常会使它们更容易理解和测试。