Python math.fmod() 方法



Python 的math.fmod()方法用於計算一個數字除以另一個數字的浮點餘數。在數學上,它計算第一個引數(被除數)除以第二個引數(除數)時的餘數,其中兩個引數都是浮點數。

使用fmod()方法計算餘數的公式為:

fmod(x,y) = x − y × ⌊x/y⌋

其中,⌊x/y⌋表示小於或等於x/y的最大整數。例如,如果x = 10.5且y = 3.0,則math.fmod(10.5, 3.0)返回10.5 − 3.0 × ⌊10.5/3.0⌋ = 1.5。

語法

以下是 Python math.fmod()方法的基本語法:

math.fmod(x, y)

引數

此方法接受以下引數:

  • x − 表示分子的數值。

  • y − 表示分母的數值。

返回值

該方法返回一個浮點數,即x除以y的餘數。結果的符號與x的符號相同,而與y的符號無關。

示例 1

在以下示例中,我們使用math.fmod()方法計算10除以3的餘數:

import math
result = math.fmod(10, 3)
print("The result obtained is:",result) 

輸出

獲得的輸出如下:

The result obtained is: 1.0

示例 2

當將負被除數傳遞給fmod()方法時,它將返回與被除數符號相同的符號的結果。

在這裡,我們使用math.fmod()方法計算-10除以3的餘數:

import math
result = math.fmod(-10, 3)
print("The result obtained is:",result) 

輸出

以下是上述程式碼的輸出:

The result obtained is: -1.0

示例 3

如果我們將浮點數作為被除數和除數都傳遞,fmod()方法將返回一個浮點值:

import math
result = math.fmod(7.5, 3.5)
print("The result obtained is:",result) 

輸出

我們得到如下所示的輸出:

The result obtained is: 0.5

示例 4

當將負除數傳遞給fmod()方法時,它將保留被除數的符號。

現在,我們使用math.fmod()方法計算10除以-3的餘數:

import math
result = math.fmod(10, -3)
print("The result obtained is:",result) 

輸出

產生的結果如下所示:

The result obtained is: 1.0
python_maths.htm
廣告