使用 scipy.quad 评估卷积积分

时间:2021-06-09 08:55:10

标签: python-3.x scipy quad

我有一个 {x2} 值的数据集,其中两个数组 f[x2] 和 g[x2] 是已知的。数据集{x2}不是均匀间隔的;我想使用这些已知样本评估 f,g 的卷积积分。一个最小的代码是这样的:

#irregular grid for data points
x2  = np.geomspace( 5, 10, 100 )
x2n =-np.flip( x2 )
x2  = np.concatenate( ( x2n, x2 ) )
x2  = np.concatenate(  (np.array([0.0]) , x2 ), axis=0 )
x_inner = np.linspace( -5,5, 1000 )
x2 = np.concatenate( ( x_inner, x2 ) )    
x2  = np.sort(x2)
   
f2  = np.zeros( x2.shape[0], dtype=np.complex128 )
f2[ np.abs(x2)<=2 ] = 1.0 + 2j

g2 = np.zeros( x2.shape[0], dtype=np.complex128 )
g2 = np.sin( x2**3 )*np.exp( -x2**2 ) + 1j*np.sin( x2 )*np.exp( -x2**2 )      
           
def fg_x( f, g ):
    return f*g

def convolution_quad( f , g ):
    
    return quad(  fg_x, -np.inf, np.inf, args=(g)  )
    
    
from scipy.integrate import quad

#evaluate convolution of the two arrays over the irregular sample data x2
res2 = convolution_quad( f2, g2)

然而,这个函数调用根本不起作用,它给出了错误:

 return _quadpack._qagie(func,bound,infbounds,args,full_output,epsabs,epsrel,limit)
 TypeError: only size-1 arrays can be converted to Python scalars

如何使用 scipy 的四边形计算离散数据集上的这种卷积积分?可以使用梯形规则或辛普森规则来评估此类积分,但在这里我正在寻找准确的评估。

1 个答案:

答案 0 :(得分:1)

quad 将需要一个连续函数作为输入。 由于您的数据是离散的,因此您应该使用离散卷积 numpy.convolve

res2 = np.convolve(f2, g2)