如何集成数组定义的函数

问题描述 投票:0回答:1

我根据以下代码构造并绘制了一个由数组定义的函数:

# set parameters
mean   = np.array([0, 3])   
sigma  = np.array([1, .8])  
weight = np.array([.4, .6])  
factor = 4
points = 1000

# set limits for plot
min_plot = (mean - (factor*sigma)).min()
max_plot = (mean + (factor*sigma)).max()

# set normal  distributions
d0 = stats.norm(mean[0], sigma[0])
d1 = stats.norm(mean[1], sigma[1])

# set mixed normal
data = np.array([d0.pdf(x), d1.pdf(x)])
y = np.dot(weight, data)

# displays
x = np.linspace(min_plot, max_plot, points)
plt.plot(x, y, '-', color = 'black', label='Normal mixed')

这给了我以下情节:

请问,在两个给定值之间整合 $y$ 的最简单方法是什么,例如 $x=2$ 和 $x=4$?我知道 scipy.integrate,但不明白如何在这种特殊情况下使用它......

python scipy numerical-integration
1个回答
1
投票

您需要定义一个函数。然后您可以使用某种数值方法在指定的边界内对该函数进行积分。

我用 scipy.integrate.quad 给出一个例子:

from scipy.integrate import quad
from scipy import stats

# define function to be integrated:
def f(x):
    
    mean   = np.array([0, 3])   
    sigma  = np.array([1, .8])  
    weight = np.array([.4, .6])  
    factor = 4
    points = 1000
    
    # set normal  distributions
    d0 = stats.norm(mean[0], sigma[0])
    d1 = stats.norm(mean[1], sigma[1])

    # set mixed normal
    data = np.array([d0.pdf(x), d1.pdf(x)])
    y = np.dot(weight, data)
    
    return y

# integrate function from 2 to 4
quad(f, 2, 4)

返回

(0.4823076558823121, 5.354690645135298e-15)
,即与区间相关的积分和绝对误差。

© www.soinside.com 2019 - 2024. All rights reserved.