我有以下代码试图解决以下问题:
掷 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