成對骰子模擬
和課程中的範例類似,你將從兩個袋子各取一顆骰子,且每個袋子裡都有三顆有偏骰。
bag1 = [[1, 2, 3, 6, 6, 6], [1, 2, 3, 4, 4, 6], [1, 2, 3, 3, 3, 5]]
bag2 = [[2, 2, 3, 4, 5, 6], [3, 3, 3, 4, 4, 5], [1, 1, 2, 4, 5, 5]]
不同之處在於兩個袋子裡的骰子是成對的:如果你在 bag1 選了第二顆骰子,你也會在 bag2 選第二顆。在每次試驗中:
- 你會隨機從兩個袋子中選出一對骰子並擲出點數。
- 若
dice1和dice2的點數相加為 8,則為成功;否則為失敗。
你的任務是完成 roll_paired_biased_dice() 函式中的 for 迴圈,並使用此函式計算 dice1 與 dice2 各種點數組合的成功機率。
以下模組已為你匯入:random、將 numpy 匯入為 np、將 pandas 匯入為 pd、seaborn 匯入為 sns,以及 matplotlib.pyplot 匯入為 plt。
本練習屬於課程
Python 的 Monte Carlo 模擬
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
def roll_paired_biased_dice(n, seed=1231):
random.seed(seed)
results={}
for i in range(n):
bag_index = random.randint(0, 1)
# Obtain the dice indices
dice_index1 = ____
dice_index2 = ____
# Sample a pair of dice from bag1 and bag2
point1 = ____
point2 = ____
key = "%s_%s" % (point1,point2)
if point1 + point2 == 8:
if key not in results:
results[key] = 1
else:
results[key] += 1
return(pd.DataFrame.from_dict({'dice1_dice2':results.keys(),
'probability_of_success':np.array(list(results.values()))*100.0/n}))