我正在尝试使用scipy.integrate.simps函数执行简单的集成,我无法弄清楚它显示的结果.
这是一个MWE:
import numpy as np from scipy.integrate import simps # Same normal function used by np.random.normal def norm_func(x, mu, sigma): y = 1/(sigma*np.sqrt(2*np.pi))*np.exp(-(x-mu)**2/(2*sigma**2)) return y # Generate some random points from the normal distribution. a = np.random.normal(1., 0.1, 1000) # Integrate the evaluated values of these points. print simps(norm_func(a, 1., 0.1), a)
我希望,因为我从正态分布中抽取随机数,然后将它们的评估整合到等效的正态分布中,我应该得到积分所述正态分布的结果,即1(或非常接近它).
我找到的是结果似乎随着样本量的变化而变化a
.即使最糟糕的是,如果我设置10000的值a = np.random.normal(1., 0.1, 10000)
,则积分返回负值.
我在这做错了什么?
使用您的样本,a
首先进行排序,因为它应该是一个要采样的点数组,并且它期望它们是为了构建近似值.辛普森的规则使用
因此,它将x
从您的数组中获取值并评估函数.如果它们是随机顺序,你可以看到上面的公式没有多大意义,因为它会从域上的一个随机点到另一个随机点进行积分.将它想象为更好x
,所以我将使用该变量名称:
x = np.random.normal(1., 0.1, 1000) x.sort() # sorts in place print simps(norm_func(x, 1., 0.1), x) #0.999914876748
这对我也有用:
s = np.sort(np.random.normal(1., 0.1, 10000)) print simps(norm_func(s, 1., 0.1), s) #0.999943377731