計算NumPy陣列中所有元素的倒數
一個數的倒數定義為該數的乘法逆元,對於非零數'a',其倒數為'b',因此 a * b = 1。換句話說,'a'的倒數為'1/a'。
reciprocal() 函式
我們可以使用NumPy庫的reciprocal()函式計算陣列的倒數。此函式接受陣列作為引數,並返回給定陣列元素的倒數。結果陣列與原始陣列具有相同的形狀和大小。
語法
以下是將reciprocal()函式應用於陣列的語法。
numpy.reciprocal(x, out=None)
其中,
x 是輸入陣列。
out 是一個可選引數,表示儲存結果陣列的位置。它必須與輸入陣列具有相同的形狀。如果未提供此值,則會建立一個新陣列並將結果值儲存在其中。
示例
在下面的示例中,為了計算給定輸入陣列的倒數,我們將陣列作為引數傳遞給reciprocal()函式。
import numpy as np
a = np.array([34,23,90,34,100])
print("The input array:",a)
print("The dimension of the array:",np.ndim(a))
reci = np.reciprocal(a,dtype = float)
print("The reciprocal of the given 1-d array:",reci)
輸出
The input array: [ 34 23 90 34 100] The dimension of the array: 1 The reciprocal of the given 1-d array: [0.02941176 0.04347826 0.01111111 0.02941176 0.01 ]
示例
在下面的示例中,我們將不指定資料型別,因此預設情況下,輸出陣列的資料型別將為整數,不會返回浮點數。
import numpy as np
a = np.array([34,23,90,34,100])
print("The input array:",a)
print("The dimension of the array:",np.ndim(a))
reci = np.reciprocal(a)
print("The reciprocal of the given 1-d array:",reci)
輸出
The input array: [ 34 23 90 34 100] The dimension of the array: 1 The reciprocal of the given 1-d array: [0 0 0 0 0]
示例
這是一個使用reciprocal函式計算二維陣列元素倒數的另一個示例。
import numpy as np
a = np.array([[34,23],[90,34]])
print("The input array:",a)
print("The dimension of the array:",np.ndim(a))
reci = np.reciprocal(a,dtype = float)
print("The reciprocal of the given 2-d array:",reci)
輸出
The input array: [[34 23] [90 34]] The dimension of the array: 2 The reciprocal of the given 2-d array: [[0.02941176 0.04347826] [0.01111111 0.02941176]]
注意
reciprocal()函式的輸出陣列元素預設屬於int資料型別,因此在某些情況下,我們將只看到零作為輸出。如果我們想顯示整個浮點數作為輸出,那麼我們必須在reciprocal()函式中與陣列輸入一起指定資料型別為float。
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP