[英]Monte Carlo simulation of N dice
我正在做這個任務:
你在擲
N
骰子。 用 Python 編寫一個程序,計算總和大於3N/2
且小於9N/2
的概率。
我假設我只有 3 個骰子,因為用N
骰子制作有點復雜,我嘗試了一些東西,但我不明白如何找到9N/2 > sum > 3N/2
的概率
import random
num_throws = 20 # NT
roll_log = [0] * 12 # Generate list for dice roll tallies
for i in range(num_throws):
# Random integer between 1 and 6 inclusive for each dice
dice_1 = random.randint(1, 6)
dice_2 = random.randint(1, 6)
dice_3 = random.randint(1, 6)
# Sum the random dice and increment the tally for that particular roll total
roll_sum = dice_1 + dice_2
roll_log[roll_sum-1] += 1 # minus 1 because Python is 0-indexed
for i, tally in enumerate(roll_log):
roll_prob = float(tally) / num_throws # Experimental probability of roll
roll = i + 1 # Since Python lists are 0-indexed
print('{}: {}/{} = {}'.format(roll, tally, num_throws, roll_prob))
n = 5
m = 10
rolls_between = roll_log[n:m-1]
sum_rolls_between = sum(rolls_between)
prob_between = float(sum_rolls_between) / num_throws
我修正了第一個答案......不知道是否正確......只是修正了明顯的錯誤......
import random
N = 3
NUM_ROLLS = 10000
UPPER_BOUND = 9 * N / 2
LOWER_BOUND = 3 * N / 2
counter = 0
for _ in range(NUM_ROLLS):
s = sum([random.randint(1, 6) for _ in range(N)])
if s < UPPER_BOUND and s > LOWER_BOUND:
counter += 1
prob = 1.0 * counter / NUM_ROLLS
print "Upper Bound = ", UPPER_BOUND
print "Lower Bound = ", LOWER_BOUND
print prob
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.