日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

Numpy數值積分的實現_python

作者:微小冷 ? 更新時間: 2023-06-03 編程語言
連乘連加 元素連乘prod, nanprod;元素求和sum, nansum
累加 累加cumsum, nancumsum;累乘cumprod, nancumprod

求和

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

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

這兩種方法均被內置到了數組方法中,

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

有的時候數組中可能會出現壞數據,例如

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

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

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

為了避免這種尷尬的現象發生,numpy中提供了nansumnanprod,可以將nan排除后再進行操作

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

累加和累乘

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

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可以實現累乘操作,即

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

sum, prod相似,cumprodcumsum也提供了相應的nancumprod, nancumsum函數,用以處理存在nan的數組。

>>> 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為梯形積分求解器,同樣對于[0,1,2,3,4]這樣的數組,那么稍微對高中知識有些印象,就應該知道[0,1]之間的積分是?,此即梯形積分

>>> np.trapz(x)
8.0

接下來對比一下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()

結果如圖,可見二者差別極小。

在這里插入圖片描述

原文鏈接:https://tinycool.blog.csdn.net/article/details/128777063

  • 上一篇:沒有了
  • 下一篇:沒有了
欄目分類
最近更新