Python數字fabs()
方法返回x
的絕對值。雖然類似於abs()
函數,但兩個函數之間存在以下差異 -
abs()
是一個內置函數,而fabs()
在math
模組中定義。fabs()
函數只適用於float
和integer
類型,而abs()
也適用於複數。
語法
以下是fabs()
方法的語法 -
import math
math.fabs( x )
注意 - 此方法不能直接訪問,需要導入
math
模組,然後使用math
靜態對象調用此函數。
參數
- x - 這是一個數值。
返回值
- 此方法返回
x
的絕對值。
示例
以下示例顯示了fabs()
方法的用法。
#!/usr/bin/python3
import math # This will import math module
print ("math.fabs(-45.17) : ", math.fabs(-45.17))
print ("math.fabs(100.12) : ", math.fabs(100.12))
print ("math.fabs(100.72) : ", math.fabs(100.72))
print ("math.fabs(math.pi) : ", math.fabs(math.pi))
當運行上述程式時,它會產生以下結果 -
math.fabs(-45.17) : 45.17
math.fabs(100) : 100.0
math.fabs(100.72) : 100.72
math.fabs(math.pi) : 3.141592653589793