python-3.x - 如何使用蒙特卡罗方法模拟两个骰子
问题描述
我正在尝试使用蒙特卡罗方法模拟添加两个骰子的分布。
但是,出现了一个错误,我不知道为什么。
%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))
它总是显示“无法将类型'列表'转换为分子/分母”错误消息
解决方案
您有多个问题:
以下行将返回值(已经是一个列表)嵌套在另一个列表中:
tests = [test()]
将其更改为
tests = test()
您在函数外部初始化
dice_one
并dice_two
使用相同的值 1000 次。试试这个:dice_added = [random.randint(1,6) + random.randint(1,6) for _ in range(1000)]
推荐阅读
- android - 我的启动收到的广播接收器没有在启动时启动
- reporting-services - 我在 ssrs 中创建了一份带有日期参数的报告
- hyperledger-composer - 如何使用查询或 js 从 Hyperledger Composer 中提取唯一数据
- sql - DB2 高效的选择查询,带有许多值的 like 运算符(~200)
- python - X 列既不是 GROUPED 也不是 AGGREGATED - StandardSQL / BigQuery
- javascript - 使用 javascript 导出 html 表时更改 XLS 页边距
- sqlite - 使用 NSPersistentContainer 从 Core Data SQLite 存储中回收空间?
- html - 输入字段中的水平对齐占位符
- c# - 添加回调以发送点击事件
- php - php dechex with dark colors only