【问题标题】:Throwing n dice m times, what is the probability of getting atleast one six掷n个骰子m次,得到至少1个6的概率是多少
【发布时间】:2012-11-10 23:17:31
【问题描述】:

我有以下代码试图解决以下问题:

投n个骰子m次,计算得到至少一个6的概率。

我知道掷 2 个骰子至少得到 1 个 6 的确切概率是 11/36。

我下面的程序似乎希望概率为 0.333,这很接近,但应该是 11/36 对吧?

如果建议可以在我制作的标准代码上继续,那就太好了,但也感谢矢量化代码。

import random
from sys import argv

m = int(argv[1]) # performing the experiment with m dice n times
n = int(argv[2]) # Throwing m dice n times
s = 0            # Counts the number of times m dies shows at least one 6

print '%.g dice are thrown %.g times' % (m, n)

for i in xrange(n):
    list = []    # used to clear the list for new die count
    for q in xrange(m):
        r = random.randint(1,6)#Picks a random integer on interval [1,6]
        list.append(r)         #appends integer value
        if len(list) == m:     #when list is full, that is when m dice has been thrown
            for i in xrange(len(list)):
                #print list
                if list[i] == 6: #if the list of elements has a six add to the counter
                    s += 1
                    pass #I want the loop to exit when it finds an element = 6

print 'Number of times one of the n dice show at least one 6: %.g' % s  
print 'Probability of at least 1 six from %.g dice is = %2.3f' % (m,s/float(n))

如果有不清楚的地方,我会编辑代码和问题。

输出样本:

Terminal > python one6_ndice.py 2 1000000
2 dice are thrown 1e+06 times
Number of times one of the n dice show atleast one 6: 3e+05
Probability of atleast 1 six from 2 dice is = 0.333

【问题讨论】:

    标签: python-2.7 probability standard-library dice


    【解决方案1】:

    我认为问题出在这里:

     pass #I want the loop to exit when it finds an element = 6
    

    pass 不会退出循环。 pass 为无操作指令;它什么都不做。您可能想要break(退出循环)。

    顺便说一句,不要调用你的列表list——这会破坏内置的list

    对于更紧凑的表达式,您可以考虑

    sum(any(random.randint(1,6) == 6 for die in xrange(n)) for trial in xrange(m))
    

    sum(6 in (random.randint(1,6) for die in range(n)) for trial in range(m))
    

    【讨论】:

    • 感谢您的建议和pass/loop的启发。这似乎已经解决了一切。顺便说一句,如果我选择了最佳答案,是否仍然可以回答问题?
    • @Palaios:是的,人们可以继续回答。
    【解决方案2】:

    您不必在列表上循环,也不必检查它的长度。只需喂它并检查其中是否有 6:

    for i in xrange(n):
        list = []
        for q in xrange(m):
            r = random.randint(1, 6)
            list.append(r)
        if 6 in list:
            s += 1
    

    如果您希望您的程序更紧凑并且不想每次都输入一个列表,您可以在获得“6”时使用break 停止生成:

    for i in xrange(n):
        for q in xrange(m):
            if random.randint(1, 6) == 6:
                s += 1
                break
    

    【讨论】:

    • 太棒了,我将尝试实现它以使我的代码更具可读性。
    猜你喜欢
    • 2010-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-11
    • 2016-07-08
    • 1970-01-01
    • 2021-04-04
    相关资源
    最近更新 更多