【发布时间】:2020-05-13 00:54:02
【问题描述】:
因此,我试图通过每次使用相同数量的不同随机数重复模拟来创建一个 pi 测量数据集,并将该数据集绘制为直方图。
我做的第一件事是使用蒙特卡洛方法估计 pi。我使用了 N = 1000 个随机数(见下面的代码)。然后我创建了一个空列表,稍后将存储 pi 值。之后,我创建了另一个范围为 100 的 for 循环并嵌套 我创建的 for 循环在新的 for 循环下估计 pi(范围为 1000)(参见下面的代码)。我不知道这是否是创建数据集的正确方法。请纠正我。
[...importing modules (random, numpy and matplotlib)...]
N= 1000 #total number of points
M = 100 #number of pi values
red_points_x = []
red_points_y = []
blue_points_x = []
blue_points_y = []
##Pi estimation
for i in range(N):
x = np.random.rand()*2 -1
y = np.random.rand()*2 -1
if x**2 + y**2 <= 1:
red_points_x.append(x)
red_points_y.append(y)
else:
blue_points_x.append(x)
blue_points_y.append(y)
pi_mc = (4.0*(len(red_points_x)))/N
print(pi_mc)
#Creating a data set for pi
list_of_pis = []
for i in range(M):
for j in range(N):
x = np.random.rand()*2 -1
y = np.random.rand()*2 -1
if x**2 + y**2 <= 1:
red_points_x.append(x)
red_points_y.append(y)
else:
blue_points_x.append(x)
blue_points_y.append(y)
#pi = (4.0*(len(red_points_x)))/N
list_of_pis.append(pi)
print(list_of_pis)
但是我得到了错误的 pi 值(见下文)。
输出:
[313.06, 313.06, 313.06, 313.06, 313.06, 313.06, 313.06, 313.06, 313.06, 313.06, 313.06, 313.06, 313.06, 313.06, 313.06, 313.06, 313.06, 313.06, 313.06, 313.06, 313.06, 313.06, 313.06, 313.06,...]
基本上,我要做的是多次计算 pi 并将计算得到的 pi 分布直方图(应该大致对称并在 pi 附近达到峰值)。
我希望我的代码不会太长。我试图尽可能地减少它,但我包含的代码部分非常重要。请帮助,您的帮助将不胜感激。非常感谢您。
【问题讨论】:
-
你注释掉了计算 pi 值的那一行
标签: python python-3.x loops matplotlib montecarlo