我有一个二维数组。“xy”平面是从 (-1,-1) 到 (1,1) 的网格。我想在函数取决于点坐标的每个点计算和积分。
我知道对于离散数据,我可以使用 simps 或 trapz 并指定一个轴来整合(参见示例)。scipy.integrate.quad 是否可以在不使用如下所示的丑陋循环的情况下做到这一点?
import numpy as np
import scipy as sp
import scipy.integrate
x = np.linspace(-1, 1, 10)
y = np.linspace(-1, 1, 10)
X,Y = np.meshgrid(x, y)
z = np.linspace(1, 10, 100)
# Integrate discrete values using simps
def func(z):
return (X - z) / ((X - z)**2. + Y**2)
res1 = sp.integrate.simps(func(z.reshape(-1, 1, 1)), z, axis=0)
print(res1)
# Integrate the function using quad at each point in the xy plane
res2 = np.zeros(X.shape)
for i in range(res2.shape[0]):
for j in range(res2.shape[1]):
def func2(z):
return (X[i,j] - z) / ((X[i,j] - z)**2. + Y[i,j]**2)
res2[i,j] = sp.integrate.quad(func2, 1, 10)[0]
print(res2)