前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >NumPy 实现梯形法积分

NumPy 实现梯形法积分

作者头像
用户2183996
发布2018-06-21 17:35:35
1.5K0
发布2018-06-21 17:35:35
举报
文章被收录于专栏:技术沉淀技术沉淀技术沉淀

使用梯形法计算一二次函数的数值积分

$\int_{a}^{b}f(x)dx$

we can partition the integration interval $[a,b]$ into smaller subintervals, and approximate the area under the curve for each subinterval by the area of the trapezoid created by linearly interpolating between the two function values at each end of the subinterval:

The blue line represents the function $f(x)$ and the red line is the linear interpolation. By subdividing the interval $[a,b]$, the area under $f(x)$ can thus be approximated as the sum of the areas of all the resulting trapezoids.

If we denote by $x_{i}$ ($i=0,\ldots,n,$ with $x_{0}=a$ and $x_{n}=b$) the abscissas where the function is sampled, then

$$ \int_{a}{b}f(x)dx\approx\frac{1}{2}\sum_{i=1}{n}\left(x_{i}-x_{i-1}\right)\left(f(x_{i})+f(x_{i-1})\right). $$

The common case of using equally spaced abscissas with spacing $h=(b-a)/n$ reads simply

$$ \int_{a}{b}f(x)dx\approx\frac{h}{2}\sum_{i=1}{n}\left(f(x_{i})+f(x_{i-1})\right). $$ 具体计算只需要这个公式

积分
积分

积分

道理很简单,就是把积分区间分割为很多小块,用梯形替代,其实还是局部用直线近似代替曲线的思想。这里对此一元二次函数积分,并与python模块积分制对比(精确值为4.5)用以验证。 $$ \int_a^b (x^2 - 3x + 2) dx $$

from scipy import integrate
def f(x):
    return x*x - 3*x + 2

def trape(f,a,b,n=100):
    f = np.vectorize(f) # can apply on vector
    h = float(b - a)/n
    arr = f(np.linspace(a,b,n+1))
    return (h/2.)*(2*arr.sum() - arr[0] - arr[-1])

def quad(f,a,b):
    return integrate.quad(f,a,b)[0] # compare with python library result
a, b = -1, 2
print trape(f,a,b)
print quad(f,a,b)
4.50045
4.5
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2016.06.27 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 使用梯形法计算一二次函数的数值积分
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档