【Python】Numpy数值积分 |
您所在的位置:网站首页 › python累加计算 › 【Python】Numpy数值积分 |
文章目录
求和累加和累乘trapz
连乘连加元素连乘prod, nanprod;元素求和sum, nansum累加累加cumsum, nancumsum;累乘cumprod, nancumprod;
求和
在Numpy中可以非常方便地进行求和或者连乘操作,对于形如 x 0 , x 1 , ⋯ , x n x_0,x_1,\cdots,x_n x0,x1,⋯,xn的数组而言,其求和 ∑ x i \sum x_i ∑xi或者连乘 ∏ x i \prod x_i ∏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()效果如图所示 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.]) trapzcumsum操作是比较容易理解的,可以理解为离散化的差分,比如 >>> 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 + 0 2 = 1 2 \frac{1+0}{2}=\frac{1}{2} 21+0=21,此即梯形积分 >>> 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()结果如图,可见二者差别极小。 |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |