【Python】Numpy数值积分

连乘连加元素连乘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分别通过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]之间的积分是 1 + 0 2 = 1 2 \frac{1+0}{2}=\frac{1}{2} 21+0=21,此即梯形积分

>>> 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()

结果如图,可见二者差别极小。
在这里插入图片描述

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

微小冷

请我喝杯咖啡

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值