首页 > 解决方案 > 如何使用蒙特卡罗方法模拟两个骰子

问题描述

我正在尝试使用蒙特卡罗方法模拟添加两个骰子的分布。

但是,出现了一个错误,我不知道为什么。

%matplotlib inline
import matplotlib.pyplot as plt
import pandas as pd
import random
from statistics import mean, stdev

die_one = random.randint(1,6)

die_two = random.randint(1,6)

def test():

    dice_added = [die_one + die_two for _ in range(1000)]

    return dice_added

tests = [test()]

plt.hist(mean(tests))

它总是显示“无法将类型'列表'转换为分子/分母”错误消息

标签: python-3.xfunctioniterable

解决方案


您有多个问题:

  1. 以下行将返回值(已经是一个列表)嵌套在另一个列表中:

    tests = [test()]
    

    将其更改为

    tests = test()
    
  2. 您在函数外部初始化dice_onedice_two使用相同的值 1000 次。试试这个:

    dice_added = [random.randint(1,6) + random.randint(1,6) for _ in range(1000)]
    

推荐阅读