Python 3.4 scipy integration.quad dropoff [英] Python 3.4 scipy integrate.quad dropoff

查看:39
本文介绍了Python 3.4 scipy integration.quad dropoff的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 python 中计算高斯的积分,如下所示:

I'm trying to compute the integral of a Gaussian in python like so:

from math import exp
from scipy import stats, integrate
import scipy.interpolate as interpolate
from numpy import cumsum, random, histogram, linspace, zeros, inf, pi,sqrt
import matplotlib.pyplot as plt

A = 1
mu = 0
sigma = 1
p = lambda x: A * exp(-(((x-mu)**2))/(2*(sigma**2)))
F = lambda x: integrate.quad(p, -inf, x)[0]
Ns = 1000;
x = linspace(-50,50,Ns);
y = zeros(Ns)
yy = zeros(Ns)
for i in range(Ns):
    y[i] = F(x[i])
    yy[i]= p(x[i])

plt.plot(x,y)
plt.plot(x,yy)
plt.show()

但如果看图,在 21.0 到 22 之间和 38+ 之后下降到零.有谁知道它为什么这样做?可能是四舍五入错误?

but if one looks on the plot, there is a drop to zero between the range 21.0 to 22, and after 38+. does anyone know why it is doing that? Rounding errors perhaps?

谢谢!!

推荐答案

我认为理解这个问题的关键是记住数值积分方法计算特定节点处函数值的加权和.

I think the key to understand this problem is to recall that numerical integration methods calculate a weighted sum of function values at specific knots.

当您偏离均值时,高斯函数会迅速变为零,因此基本上在 (-50, 50) 之间的区间上,大多数函数值都为零.如果积分方法无法从函数非零的小区域中采样点,它会将整个函数视为完全平坦的,从而为您提供积分 0.

The gaussian quickly goes to zero as you deviate from the mean, so basically on the interval between (-50, 50) most of the function values are zero. If the integration method fails to sample points from your small area where the function is non-zero, it will see the whole function as completely flat and thus gives you the integral 0.

那你能做什么?

不要选择 (-50,50) 的固定区间,而是选择基于较小 sigma 值的区间,以避免在过大的零区间上进行积分.

Instead of choosing the fixed interval of (-50,50), choose an interval based on smaller sigma values, to avoid integrating over an overly large interval of zeros.

如果您只向左和向右移动 5、10 或 20 个标准差,您就不会看到这个问题,并且您仍然可以获得非常准确的积分结果.

If you go only 5, 10 or 20 standard deviations to the left and to the right, you will not see this issue, and you still have a very accurate integration result.

这是从 10 个标准差向左和向右积分的结果.

This is the result if you integrate from 10 standard deviations to the left and to the right.

这篇关于Python 3.4 scipy integration.quad dropoff的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆