模拟一对骰子的重复卷直到获得100卷r;然后打印卷数

时间:2015-11-10 05:36:58

标签: python while-loop probability dice

我正在计算获得100卷两个骰子r(2-12)所需的卷数并打印出来。这是我到目前为止所尝试的:

from random import randrange
def diceprob(r):
    count = 0

    while count < 100:
        roll = random.randrange(2, 13)
        if roll == r:
            count += 1
    print("It took {} rolls to get 100 rolls of {}".format(count, r))

但是当它跑完时,它总是打印出来,“它需要100卷才能获得100卷5”,其中5的值根据所谓的r而变化。为什么计数没有正确递增?

2 个答案:

答案 0 :(得分:2)

你在计算得到r的卷,而不是所有卷。 另请注意,两个六面骰子卷的总和分布不均匀,因此您需要拨打random.randrange(1, 7)两次

import random
def diceprob(r):
    total_count = 0
    count = 0

    while count < 100:
        roll = random.randrange(1, 7) + random.randrange(1, 7)
        total_count += 1
        if roll == r:
            count += 1
    print("It took {} rolls to get 100 rolls of {}".format(total_count, r))

如果我们为diceprob的各种值调用r,我们就会得到结果

It took 3849 rolls to get 100 rolls of 2
It took 1932 rolls to get 100 rolls of 3
It took 1394 rolls to get 100 rolls of 4
It took 881 rolls to get 100 rolls of 5
It took 717 rolls to get 100 rolls of 6
It took 537 rolls to get 100 rolls of 7
It took 748 rolls to get 100 rolls of 8
It took 798 rolls to get 100 rolls of 9
It took 1295 rolls to get 100 rolls of 10
It took 1881 rolls to get 100 rolls of 11
It took 3689 rolls to get 100 rolls of 12

将其与the distribution

的图表进行比较

答案 1 :(得分:0)

您需要两个变量,一个用于总卷,另一个用于等于r的卷。你只计算等于r的卷,只打印那个。

def diceprob(r):
    total = 0
    count = 0
    while count < 100:
        roll = random.randrange(2, 13)
        total++
        if roll == r:
            count++
    print("It took {} rolls to get {} rolls of {}".format(total, count, r))

还有一个单独的问题,即你正在推动一个11面骰子(数字从2到12),而不是两个6面骰子。