使用 NumPy 返回被除數和除數陣列的餘數


要返回逐元素的除法餘數,請在 Python NumPy 中使用 **numpy.remainder()** 方法。這裡,第一個引數是被除數陣列。第二個引數是除數陣列。計算與 floor_divide 函式互補的餘數。它等效於 Python 模運算子“x1 % x2”,並且與除數 x2 的符號相同。等效於 np.remainder 的 MATLAB 函式是 mod。

out 是將結果儲存到的位置。如果提供,則其形狀必須是輸入廣播到的形狀。如果沒有提供或為 None,則返回一個新分配的陣列。元組(僅可能作為關鍵字引數)的長度必須等於輸出的數量。

步驟

首先,匯入所需的庫:

import numpy as np

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

arr = np.array([3, 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([5, 7, 3, 2, 2, 7, 7])

要返回逐元素的除法餘數,請使用 numpy.remainder() 方法。這裡,第一個引數是被除數陣列。第二個引數是除數陣列:

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

示例

import numpy as np

# Create an array
# This is the dividend array
arr = np.array([3, 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([5, 7, 3, 2, 2, 7, 7]) # To return the element-wise remainder of division, use the numpy.remainder() method in Python Numpy # Here, the 1st parameter is the Dividend array # The 2nd parameter is the Divisor array print("
Result (remainder)...
",np.remainder(arr, divisor))

輸出

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

Our Array type...
int64

Our Array Dimension...
1

Our Array Shape...
(7,)

Result (remainder)...
[3 2 2 0 0 4 0]

更新於:2022年2月8日

瀏覽量:129

啟動您的 職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.