连乘连加 |
元素连乘prod, nanprod ;元素求和sum, nansum |
累加 |
累加cumsum, nancumsum ;累乘cumprod, nancumprod ; |
求和
在Numpy中可以非常方便地进行求和或者连乘操作,对于形如 x 0 , x 1 , ⋯ , xn的数组而言,其求和 ∑xi或者连乘 ∏xi分别通过sum
和prod
实现。
1
2
3
|
x = np.arange( 10 ) print (np. sum (x)) # 返回45 print (np.prod(x)) # 返回0 |
这两种方法均被内置到了数组方法中,
1
2
3
|
x + = 1 x. sum () # 返回55 x.prod() # 返回3628800 |
有的时候数组中可能会出现坏数据,例如
1
2
3
|
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
就会像下面这样
1
2
3
4
|
>>> x. sum () nan >>> x.prod() nan |
为了避免这种尴尬的现象发生,numpy
中提供了nansum
和nanprod
,可以将nan
排除后再进行操作
1
2
3
4
|
>>> np.nansum(x) 9.0 >>> np.nanprod(x) 1.0 |
累加和累乘
和连加连乘相比,累加累乘的使用频次往往更高,尤其是累加,相当于离散情况下的积分,意义非常重大。
1
2
3
4
5
6
7
|
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
可以实现累乘操作,即
1
2
3
|
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
的数组。
1
2
3
4
5
6
7
8
|
>>> 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
操作是比较容易理解的,可以理解为离散化的差分,比如
1
2
3
4
5
6
|
>>> 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]
之间的积分是,此即梯形积分
1
2
|
>>> np.trapz(x) 8.0 |
接下来对比一下trapz
和cumsum
作用在 sin x sin x sinx上的效果
1
2
3
4
5
6
7
8
|
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() |
结果如图,可见二者差别极小。
到此这篇关于Numpy数值积分的实现的文章就介绍到这了,更多相关Numpy数值积分内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!
原文链接:https://tinycool.blog.csdn.net/article/details/128777063