成对骰子模拟
与课中示例类似,您将从两个袋子中各取一个骰子来掷,每个袋子里都有 3 个有偏骰子。
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 中的蒙特卡洛模拟
交互式实操练习
通过完成这段示例代码来试试这个练习。
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}))