日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > python >内容正文

python

python求积分基于numpy_NumPy 实现梯形法积分

發(fā)布時間:2023/12/19 python 35 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python求积分基于numpy_NumPy 实现梯形法积分 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

使用梯形法計算一二次函數(shù)的數(shù)值積分

$\int_{a}^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}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}f(x)dx\approx\frac{h}{2}\sum_{i=1}{n}\left(f(x_{i})+f(x_{i-1})\right).

$$

具體計算只需要這個公式

積分

道理很簡單,就是把積分區(qū)間分割為很多小塊,用梯形替代,其實還是局部用直線近似代替曲線的思想。這里對此一元二次函數(shù)積分,并與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

總結(jié)

以上是生活随笔為你收集整理的python求积分基于numpy_NumPy 实现梯形法积分的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。