简体   繁体   English

使用Simpson规则整合正态分布

[英]Integration of normal distribution using Simpson's rule

I'm trying to perform a simple integration using the scipy.integrate.simps function and I can't figure out the results it shows. 我正在尝试使用scipy.integrate.simps函数执行简单的集成,但我无法弄清楚它显示的结果。

Here's a MWE: 这是一个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)

I would expect that since I'm drawing random numbers from a normal distribution and then integrating their evaluation in an equivalent normal distribution, I should get the result of integrating said normal distribution which is 1 (or very close to it). 我希望,因为我是从正态分布中提取随机数,然后将其评估结果整合到等效的正态分布中,所以我应该得到将所述正态分布整合为1 (或非常接近)的结果。

What I find instead is that the results appear to vary with the sample size of a . 我觉得反而是,结果显示用的样本量来改变a Even worst, if I set a value of 10000 in a = np.random.normal(1., 0.1, 10000) , the integration returns a negative value. 更糟糕的是,如果我在a = np.random.normal(1., 0.1, 10000)值设置为10000,则积分将返回负值

What am I doing wrong here? 我在这做错了什么?

Using your sample, just sort a first, since it should be an array of points to sample at, and it expects them to be in order to build the approximation. 使用您的样品,只是排序a第一,因为它应该是一个点的数组的采样,并希望他们是为了建立近似。 Simpson's rule uses 辛普森的规则使用

辛普森一家

So it will be taking values for x from your array and evaluating the function. 因此,它将从您的数组中获取x值并评估函数。 If they are in a random order you can see that the above formula makes little sense, as it will do integrals from one random point on the domain to another. 如果它们是随机顺序,你可以看到上面的公式没有多大意义,因为它会从域上的一个随机点到另一个随机点进行积分。 It might be better to think of it as x , so I'll use that variable name: 最好将其视为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

This also works for me: 这对我也有用:

s = np.sort(np.random.normal(1., 0.1, 10000))
print simps(norm_func(s, 1., 0.1), s)
#0.999943377731

Here is how you can integrate the standard normal pdf using simps : 以下是如何使用simps集成标准普通pdf:

In [37]: a = np.linspace(-20, 20)

In [38]: print simps(norm_func(a, 0., 1.), a)
1.0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM