使用 NumPy 中的 fmod() 函式返回除法的元素級餘數


要返回除法的元素級餘數,請在 Python NumPy 中使用 **numpy.fmod()** 方法。對於 fmod,結果的符號與被除數的符號相同。**fmod()** 函式等效於 Matlab(TM) 的 rem 函式。這裡,第一個引數是被除數陣列。第二個引數是除數陣列。

這是 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])

要返回除法的元素級餘數,請在 Python NumPy 中使用 numpy.fmod() 方法。對於 fmod,結果的符號與被除數的符號相同。fmod 函式等效於 Matlab(TM) 的 rem 函式。這裡,第一個引數是被除數陣列。第二個引數是除數陣列 -

print("
Result...
",np.fmod(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 remainder of division, use the numpy.fmod() method in Python Numpy # For fmod, the sign of result is the sign of the dividend # The fmod function is equivalent to the Matlab(TM) rem function. # Here, the 1st parameter is the Dividend array # The 2nd parameter is the Divisor array print("
Result...
",np.fmod(arr, divisor))

輸出

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

Our Array type...
int64

Our Array Dimension...
1

Our Array Shape...
(7,)

Result...
[-2 2 2 -1 0 4 0]

更新於: 2022年2月8日

212 次檢視

啟動你的 職業生涯

透過完成課程獲得認證

開始學習
廣告