您好,登錄后才能下訂單哦!
本篇內(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分別通過sum
和prod
實(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
中提供了nansum
和nanprod
,可以將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()
效果如圖所示
cumprood
可以實(shí)現(xiàn)累乘操作,即
x = np.arange(1, 10) print(np.cumprod(x)) # [ 1 2 6 24 120 720 5040 40320 362880]
與sum, prod
相似,cumprod
和cumsum
也提供了相應(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.])
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]
之間的積分是,此即梯形積分
>>> np.trapz(x) 8.0
接下來對(duì)比一下trapz
和cumsum
作用在 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é)果如圖,可見二者差別極小。
到此,相信大家對(duì)“Numpy數(shù)值積分如何實(shí)現(xiàn)”有了更深的了解,不妨來實(shí)際操作一番吧!這里是億速云網(wǎng)站,更多相關(guān)內(nèi)容可以進(jìn)入相關(guān)頻道進(jìn)行查詢,關(guān)注我們,繼續(xù)學(xué)習(xí)!
免責(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)容。