網站首頁 編程語言 正文
連乘連加 | 元素連乘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()
效果如圖所示
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) <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
接下來對比一下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()
結果如圖,可見二者差別極小。
原文鏈接:https://tinycool.blog.csdn.net/article/details/128777063
- 上一篇:沒有了
- 下一篇:沒有了
相關推薦
- 2023-07-06 mybatis-plus 分頁查詢出現count()而不是count(*)
- 2022-10-17 Kotlin編程基礎語法編碼規范_Golang
- 2022-04-08 一起來看看五條Python中的隱含特性_python
- 2022-12-22 Qt實現繪制一個簡單多邊形的示例代碼_C 語言
- 2022-10-22 C#?設置Chart的X軸為時間軸???????詳情_C#教程
- 2022-04-22 mac解決npm不管裝啥都是zsh: command not found
- 2022-06-10 python?PIL?Image?圖像處理基本操作實例_python
- 2022-06-28 C++哈希表之線性探測法實現詳解_C 語言
- 欄目分類
-
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支