[英]Monte Carlo simulation dices in python
我有一個基於滾動2個骰子的概率與蒙特卡洛模擬有關的問題。 當用python編碼時,如何顯示和大於n小於m的事實? 作為示例,我在mathlab中進行了此操作:
NT = 10^5; %number of throws
log = zeros(1,12);
for throw = 1:NT
dices = ceil(6*rand(1,2));
s = sum(dices);
log(s) = log(s)+1;
end
p = 36*log(6:9)/NT;
s1 = sum(round(p))
在上面的示例中,我假設n為5,m為10。
謝謝
見下文-
import numpy as np
NT = 10**5
n=5
m=10
x = np.random.randint(1, 12, NT)
s = sum((x>=n) & (x<=m))
p = s*1.0/NT
print(p)
在每個循環中,您要模擬兩個單獨的隨機骰子投擲。 我的以下代碼段使用一個list
(如果願意,可以使用dict
)存儲NT
模擬的結果:
import random
num_throws = 10**5 # 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)
# 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
要處理您的結果數據,您可以通過roll_log[roll-1]
訪問結果列表中特定骰子擲骰的計數,其中2 <= roll <= 12
( roll = 1
的概率為零,因為2不可能+骰子)。 下面的for循環只是不熟悉Python枚舉的情況下如何訪問NT
模擬結果的示例:
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))
輸出:
1: 0 / 100000 = 0
2: 2741 / 100000 = 0.02741
3: 5518 / 100000 = 0.05518
4: 8202 / 100000 = 0.08202
5: 11235 / 100000 = 0.11235
6: 14046 / 100000 = 0.14046
7: 16520 / 100000 = 0.1652
8: 13799 / 100000 = 0.13799
9: 11025 / 100000 = 0.11025
10: 8459 / 100000 = 0.08459
11: 5672 / 100000 = 0.05672
12: 2783 / 100000 = 0.02783
專門解決問題的最后一部分,找出骰子擲骰的概率在n = 5
和m = 10
不包括在內),可以使用稱為列表切片的方法來完成:
n = 5
m = 10
# 6 7 8 9
rolls_between = roll_log[n:m-1] # [14046, 16520, 13799, 11025]
sum_rolls_between = sum(rolls_between) # 55390
prob_between = float(sum_rolls_between) / num_throws # 0.5539
注意:最后一行的sum_rolls_between
或num_throws
的float
轉換對於獲取十進制輸出是必不可少的,因為在應用數學floor()
函數后,Python中兩個整數之間的除法始終會導致整數輸出。 換句話說,如果不將這兩個值之一更改為浮點值,則結果將為0。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.