一维情况下,若要计算 ∫ 0 1 f ( x ) d x \int_{0}^1 f(x) dx ∫01f(x)dx, 首先在被积分区域生成x,然后计算对应的 f ( x ) f(x) f(x), 然后用np.trapz()函数计算。
import numpy as np
x = np.linspace(0, 1, 10000)
y = x**2
int_y = np.trapz(y, x)
print(int_y)
二维情况下,要计算 ∫ Ω f ( x , y ) d x d y \int_{\Omega} f(x,y) dxdy ∫Ωf(x,y)dxdy, 就先对某个维度积分,再对另一个维度进行积分,这里要注意f的算法。
## trapz test for 2D:
#
x = np.linspace(0, 1, 100)
y = np.linspace(0, 1, 100)
X, Y = np.meshgrid(x, y)
#
f = X**2 + Y**2# take f(x, y) = x^2 + y^2
# first, integrate over the y-direction
int_y = np.trapz(f, y, axis=0)
# integrate over the x-direction
int_xy = np.trapz(int_y, x)
print('2D case')
print('integral result:',int_xy)
print('presicion:', int_xy -2/3)