Python math.fabs() 方法



Python 的 math.fabs() 方法用於計算數字的浮點數絕對值。此方法的結果永不為負;即使數字為負值,該方法也會返回其相反數。

與 abs() 方法不同,fabs() 方法的結果始終為浮點型別;並且它不接受複數作為引數。

注意 - 此函式無法直接訪問,因此我們需要匯入 math 模組,然後使用 math 靜態物件呼叫此函式。

語法

以下是 Python math.fabs() 方法的語法:

math.fabs( x )

引數

  • x - 這是一個數值。

返回值

此方法返回 x 的浮點型絕對值。

示例

以下示例演示了 Python math.fabs() 方法的用法。在這裡,讓我們嘗試計算正實數的絕對值。

import math

# Create positive Integer and Float objects
inr = 45
flt = 100.12

# Calculate the absolute values of the objects
abs_int = math.fabs(inr)
abs_flt = math.fabs(flt)

# Print the values
print("Absolute Value of an Integer:", abs_int)
print("Absolute Value of an Float:", abs_flt)

執行上述程式時,會產生以下結果:

Absolute Value of an Integer: 45.0
Absolute Value of an Float: 100.12

示例

正如我們已經討論過的,絕對值只考慮數字的大小。因此,在這個例子中,我們建立了具有負值的數字物件,並嘗試使用 fabs() 方法計算它們的浮點型絕對值。

import math

# Create negative Integer and Float objects
inr = -34
flt = -154.32

# Calculate the absolute values of the objects
abs_int = math.fabs(inr)
abs_flt = math.fabs(flt)

# Print the values
print("Absolute Value of an Integer:", abs_int)
print("Absolute Value of an Float:", abs_flt)

讓我們編譯並執行上面的程式,輸出結果如下:

Absolute Value of an Integer: 34.0
Absolute Value of an Float: 154.32

示例

如果我們將複數作為引數傳遞給此方法,則會引發 TypeError。

在下面的示例中,我們建立了兩個儲存複數的物件,一個正數,另一個負數;然後將其作為引數傳遞給此方法。

import math

# Create positive and negative complex number objects
pos_cmplx = 12-11j
neg_cmplx = -34-56j

# Calculate the absolute values of the objects created
abs1 = math.fabs(pos_cmplx)
abs2 = math.fabs(neg_cmplx)

# Print the return values
print("Absolute Value of a positive complex number:", abs1)
print("Absolute Value of a negative complex number:", abs2)

編譯並執行上面的程式,得到如下輸出:

Traceback (most recent call last):
  File "main.py", line 8, in 
abs1 = math.fabs(pos_cmplx)
TypeError: can't convert complex to float

示例

如果將 None 值作為引數傳遞給該方法,則會引發 TypeError。但是,如果將零作為引數傳遞,則該方法會返回零。

import math

# Create negative Integer and Float objects
zero = 0
null = None

# Calulate and Print the absolute values
print("Absolute Value of Zero:", math.fabs(zero))
print("Absolute Value of a Null:", math.fabs(null))

執行上述程式後,結果顯示如下:

Absolute Value of Zero: 0.0
Traceback (most recent call last):
  File "main.py", line 9, in 
    print("Absolute Value of a Null:", math.fabs(null))
TypeError: must be real number, not NoneType
python_maths.htm
廣告