目录求和累加和累乘trapz连乘连加 | 元素连乘prod, nanprod;元素求和sum, nansum | 累加 | 累加cumsum, nancumsum;累乘cumprod, nancumprod; |
求和
在Numpy中可以非常方便地进行求和或者连乘操作,对于形如 x 0 , x 1 , ⋯ , xn的数组而言,其求和 ∑xi或者连乘 ∏xi分别通过sum和prod实现。
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中提供了nansum和nanprod,可以将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()
效果如图所示
2023022309184324.png
cumprood可以实现累乘操作,即
x = np.arange(1, 10)
print(np.cumprod(x))
# [ 1 2 6 24 120 720 5040 40320 362880]
与sum, prod相似,cumprod和cumsum也提供了相应的nancumprod, nancumsum函数,用以处理存在nan的数组。
>>> x = np.arange(10)/np.arange(10)
: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]之间的积分是
202322392222860.png
,此即梯形积分
>>> np.trapz(x)
8.0
接下来对比一下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()
结果如图,可见二者差别极小。
2023022309184425.png
到此这篇关于Numpy数值积分的实现的文章就介绍到这了,更多相关Numpy数值积分内容请搜索知鸟论坛以前的文章或继续浏览下面的相关文章希望大家以后多多支持知鸟论坛! |