np.trapz梯形法则计算积分用法

一维情况下,若要计算 ∫ 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) 
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值