我有一个2D数组。 " xy" plane是从(-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)
答案 0 :(得分:1)
使用我Cubature method教授Steven Johnson的wrapped using Cython,您可以立即实现整合:
import numpy as np
from cubature import cubature
x = np.linspace(-1, 1, 10)
y = np.linspace(-1, 1, 10)
X,Y = np.meshgrid(x, y)
z = np.linspace(1, 10, 100)
def func(z):
return (X.ravel() - z) / ((X.ravel() - z)**2. + Y.ravel()**2)
res = cubature(1, func, np.array([1.]), np.array([10.]))[0].reshape(X.shape)
答案 1 :(得分:0)
使用线性间隔点效率不高。更好的想法是转向四边形的正交方案,例如here。例如:
import numpy
import quadpy
def f(x):
return (x[0] - 1) / ((x[0] - 1)**2 + x[1]**2)
quad = numpy.array([
[-1, -1],
[+1, -1],
[+1, +1],
[-1, +1],
])
scheme = quadpy.quadrilateral.Stroud(5)
val = quadpy.quadrilateral.integrate(f, quad, scheme)