溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Numpy數(shù)值積分如何實(shí)現(xiàn)

發(fā)布時(shí)間:2023-02-23 11:14:54 來源:億速云 閱讀:101 作者:iii 欄目:開發(fā)技術(shù)

本篇內(nèi)容主要講解“Numpy數(shù)值積分如何實(shí)現(xiàn)”,感興趣的朋友不妨來看看。本文介紹的方法操作簡(jiǎn)單快捷,實(shí)用性強(qiáng)。下面就讓小編來帶大家學(xué)習(xí)“Numpy數(shù)值積分如何實(shí)現(xiàn)”吧!

連乘連加元素連乘prod, nanprod;元素求和sum, nansum
累加累加cumsum, nancumsum;累乘cumprod, nancumprod

求和

在Numpy中可以非常方便地進(jìn)行求和或者連乘操作,對(duì)于形如 x 0 , x 1 , ?   , xn的數(shù)組而言,其求和 ∑xi或者連乘 ∏xi分別通過sumprod實(shí)現(xiàn)。

x = np.arange(10)
print(np.sum(x))    # 返回45
print(np.prod(x))   # 返回0

這兩種方法均被內(nèi)置到了數(shù)組方法中,

x += 1
x.sum()     # 返回55
x.prod()    # 返回3628800

有的時(shí)候數(shù)組中可能會(huì)出現(xiàn)壞數(shù)據(jù),例如

x = np.arange(10)/np.arange(10)
print(x)
# [nan  1.  1.  1.  1.  1.  1.  1.  1.  1.]

其中x[0]由于是0/0,得到的結(jié)果是nan,這種情況下如果直接用sum或者prod就會(huì)像下面這樣

>>> x.sum()
nan
>>> x.prod()
nan

為了避免這種尷尬的現(xiàn)象發(fā)生,numpy中提供了nansumnanprod,可以將nan排除后再進(jìn)行操作

>>> np.nansum(x)
9.0
>>> np.nanprod(x)
1.0

累加和累乘

和連加連乘相比,累加累乘的使用頻次往往更高,尤其是累加,相當(dāng)于離散情況下的積分,意義非常重大。

from matplotlib.pyplot as plt
xs = np.arange(100)/10
ys = np.sin(xs)
ys1 = np.cumsum(ys)/10
plt.plot(xs, ys)
plt.plot(xs, ys1)
plt.show()

效果如圖所示

Numpy數(shù)值積分如何實(shí)現(xiàn)

cumprood可以實(shí)現(xiàn)累乘操作,即

x = np.arange(1, 10)
print(np.cumprod(x))
# [     1      2      6     24    120    720   5040  40320 362880]

sum, prod相似,cumprodcumsum也提供了相應(yīng)的nancumprod, nancumsum函數(shù),用以處理存在nan的數(shù)組。

>>> x = np.arange(10)/np.arange(10)
<stdin>:1: RuntimeWarning: invalid value encountered in true_divide
>>> np.cumsum(x)
array([nan, nan, nan, nan, nan, nan, nan, nan, nan, nan])
>>> np.nancumsum(x)
array([0., 1., 2., 3., 4., 5., 6., 7., 8., 9.])
>>> np.nancumprod(x)
array([1., 1., 1., 1., 1., 1., 1., 1., 1., 1.])

trapz

cumsum操作是比較容易理解的,可以理解為離散化的差分,比如

>>> x = np.arange(5)
>>> y = np.cumsum(x)
>>> print(x)
array([0, 1, 2, 3, 4])
>>> print(y)
array([ 0,  1,  3,  6, 10])

trap為梯形積分求解器,同樣對(duì)于[0,1,2,3,4]這樣的數(shù)組,那么稍微對(duì)高中知識(shí)有些印象,就應(yīng)該知道[0,1]之間的積分是Numpy數(shù)值積分如何實(shí)現(xiàn),此即梯形積分

>>> np.trapz(x)
8.0

接下來對(duì)比一下trapzcumsum作用在 sin ? x \sin x sinx上的效果

from matplotlib.pyplot as plt
xs = np.arange(100)/10
ys = np.sin(xs)
y1 = np.cumsum(ys)/10
y2 = [np.trapz(ys[:i+1], dx=0.1) for i in range(100)]
plt.plot(xs, y1)
plt.plot(xs, y2)
plt.show()

結(jié)果如圖,可見二者差別極小。

Numpy數(shù)值積分如何實(shí)現(xiàn)

到此,相信大家對(duì)“Numpy數(shù)值積分如何實(shí)現(xiàn)”有了更深的了解,不妨來實(shí)際操作一番吧!這里是億速云網(wǎng)站,更多相關(guān)內(nèi)容可以進(jìn)入相關(guān)頻道進(jìn)行查詢,關(guān)注我們,繼續(xù)學(xué)習(xí)!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI