【发布时间】:2015-05-03 17:10:25
【问题描述】:
我正在尝试创建一个简单的数值积分函数来说明高维蒙特卡洛积分的好处。我想要这样的东西:
def quad_int(f, mins, maxs, numPoints=100):
'''
Use the naive (Riemann sum) method to numerically integrate f on a box
defined by the mins and maxs.
INPUTS:
f - A function handle. Should accept a 1-D NumPy array
as input.
mins - A 1-D NumPy array of the minimum bounds on integration.
maxs - A 1-D NumPy array of the maximum bounds on integration.
numPoints - An integer specifying the number of points to sample in
the Riemann-sum method. Defaults to 100.
'''
n = len(mins)
# Create a grid of evenly spaced points to evaluate f on
# Evaluate f at each point in the grid; sum all these values up
dV = np.prod((maxs-mins/numPoints))
# Multiply the sum by dV to get the approximate integral
我知道我的dV 会导致数值稳定性问题,但现在我遇到的问题是创建域。如果维数是固定的,那么像这样使用np.meshgrid 就很容易了:
# We don't want the last value since we are using left-hand Riemann sums
x = np.linspace(mins[0],maxs[0],numPoints)[:-1]
y = np.linspace(mins[1],maxs[1],numPoints)[:-1]
z = np.linspace(mins[2],maxs[2],numPoints)[:-1]
X, Y, Z = np.meshgrid(x,y,z)
tot = 0
for index, x in np.ndenumerate(X):
tot += f(x, Y[index], Z[index])
是否有类似于np.meshgrid 的类似物可以对任意维度执行此操作,也许可以接受数组元组?还是有其他方法可以在更高维度上进行黎曼和?我曾想过递归地执行此操作,但无法弄清楚它是如何工作的。
【问题讨论】:
标签: python arrays numpy numerical-integration