2012-11-10 79 views
0

的機率微乎其微,我有以下代碼試圖解決以下問題:投擲ñ骰子m次,是什麼讓ATLEAST一六

時拋出ň骰子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 

回答

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)) 
+0

謝謝你的建議和pass/loop啓示。這似乎已經解決了一切。順便說一句,如果我選擇一個最好的答案是否仍然有可能回答這個問題? – Palaios

+1

@Palaios:是的,人們可以繼續回答。 – DSM

1

您不必循環名單上既沒有檢查它的長度。只給它,並檢查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 

如果你希望你的程序更加緊湊,不想每次喂的列表,你可以當你得到一個與break停止發電「6」:

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

太棒了,我會試着實現這個,讓我的代碼更具可讀性。 – Palaios

+0

最後的代碼部分是輝煌的,謝謝! – Palaios