在 Python NumPy 中同時返回元素級商和餘數


要同時返回元素級的商和餘數,請在 Python NumPy 中使用 **numpy.fmod()** 方法。這裡,第一個引數是被除數陣列。第二個引數是除數陣列。

這是 C 庫函式 fmod 的 NumPy 實現,餘數與被除數 x1 具有相同的符號。它等效於 Matlab(TM) rem 函式,不應與 Python 模數運算子 x1 % x2 混淆。

條件在輸入上廣播。在條件為 True 的位置,out 陣列將設定為 ufunc 結果。在其他地方,out 陣列將保留其原始值。請注意,如果透過預設的 out=None 建立了一個未初始化的 out 陣列,則其中條件為 False 的位置將保持未初始化狀態。

步驟

首先,匯入所需的庫 -

import numpy as np

建立一個數組。這是被除數陣列 -

arr = np.array([5, 9, 14, 22, 76, 81, 91])

顯示陣列 -

print("Array...
", arr)

獲取陣列的型別 -

print("
Our Array type...
", arr.dtype)

獲取陣列的維度 -

print("
Our Array Dimension...
",arr.ndim)

獲取陣列的形狀 -

print("
Our Array Shape...
",arr.shape)

除數陣列 -

divisor = np.array([3, 7, 3, 3, 2, 7, 7])

要同時返回元素級的商和餘數,請使用 numpy.fmod() 方法。這裡,第一個引數是被除數陣列。第二個引數是除數陣列 -

print("
Result...
",np.divmod(arr, divisor))

示例

import numpy as np

# Create an array
# This is the dividend array
arr = np.array([5, 9, 14, 22, 76, 81, 91])

# Display the array
print("Array...
", arr) # Get the type of the array print("
Our Array type...
", arr.dtype) # Get the dimensions of the Array print("
Our Array Dimension...
",arr.ndim) # Get the shape of the Array print("
Our Array Shape...
",arr.shape) # Divisor array divisor = np.array([3, 7, 3, 3, 2, 7, 7]) # To return the element-wise quotient and remainder simultaneously, use the numpy.fmod() method in Python Numpy # Here, the 1st parameter is the Dividend array # The 2nd parameter is the Divisor array print("
Result...
",np.divmod(arr, divisor))

輸出

Array...
[ 5 9 14 22 76 81 91]

Our Array type...
int64

Our Array Dimension...
1

Our Array Shape...
(7,)

Result...
(array([ 1, 1, 4, 7, 38, 11, 13]), array([2, 2, 2, 1, 0, 4, 0]))

更新於: 2022年2月7日

227 次瀏覽

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告