python - 如何计算python中计算积分的误差?
问题描述
我正在使用 Monte-Carlo 方法计算积分(对于 3 个不同的 N 的 10、100、1000),但我想计算误差到积分的实际精确值(分析计算)。怎么做?如何计算积分的真实值,并绘制和打印误差值?
这是我现在使用的代码,用于使用 Monte-Carlo 方法计算积分:
a = 0
b = 2
N = np.array([10, 100, 1000])
def func(x):
return np.power(sin(1/(x*(2-x))),2)
areas = []
j = 0
while j < len(N):
for i in range(N[j]):
xrandom = np.random.uniform(a,b,N[j])
integral = 0.0
for i in range(N[j]):
integral += func(xrandom[i])
result = (b-a)/float(N[j]) * integral
areas.append(result)
plt.subplot(1,3,j+1)
plt.hist(areas, bins=30, ec='black')
j += 1
fig = plt.gcf()
fig.set_size_inches(12.5, 5.5)
plt.show()
解决方案
您可以使用scipy.integrate
,它提供了不同的积分计算方法。例如:
scipy.integrate.quad(lambda x: func(x), a, b)
推荐阅读
- php - 表 ci_session 不存在错误
- c# - 是否有可能在 asp.net mvc 5 代码优先方法中有一个可以容纳多个字符串的表列?
- dart - 谷歌登录 - Flutter
- java - 来自java的expdp命令
- google-drive-api - 使用 google drive 将视频流式传输到 html5 播放器
- c# - 时间:2019-04-10 标签:c#foreachdelegateXAMARIN ANDROID
- cluster-analysis - 如何从聚类分析结果中得出意义/价值
- python - 删除最小二叉搜索树 Python
- android - Room:如何在 DAO 接口中使用@Transaction
- c - 尝试运行一个排序 C 程序,该程序通过命令行(Mac 终端)接受输入