使用NumPy進行模運算的元素級餘數計算


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

計算相對於floor_divide函式的餘數。它等同於Python模運算子“x1 % x2”,並且與除數x2具有相同的符號。等效於np.remainder的MATLAB函式是mod。

步驟

首先,匯入所需的庫:

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.mod()方法。這裡,第一個引數是被除數陣列。第二個引數是除數陣列。

print("
Result...
",np.mod(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 with mod operation, use the numpy.mod() method in Python Numpy # Here, the 1st parameter is the Dividend array # The 2nd parameter is the Divisor array print("
Result...
",np.mod(arr, divisor))

輸出

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

Our Array type...
int64

Our Array Dimension...
1

Our Array Shape...
(7,)

Result...
[3 2 2 0 0 4 0]

更新於:2022年2月8日

348 次瀏覽

啟動您的職業生涯

完成課程獲得認證

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