以下の問題を解決しようとしている次のコードがあります。
n サイコロを m 回投げて、少なくとも 1 つの 6 が出る確率を計算します。
サイコロを 2 つ振ったときに 6 が少なくとも 1 つ出る正確な確率は 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