Python3 fabs() 函數

Python3 數字 Python3 數字


描述

fabs() 方法返回數字的絕對值,如math.fabs(-10) 返回10.0。

fabs() 函數類似於 abs() 函數,但是他有兩點區別:

  • abs() 是內置函數。 fabs() 函數在 math 模組中定義。

  • fabs() 函數只對浮點型跟整型數值有效。 abs() 還可以運用在複數中。


語法

以下是 fabs() 方法的語法:

import math

math.fabs( x )

注意:fabs()是不能直接訪問的,需要導入 math 模組,通過靜態對象調用該方法。


參數

  • x -- 數值運算式。

返回值

返回數字的絕對值。

實例

以下展示了使用 fabs() 方法的實例:

#!/usr/bin/python3
import math   # 導入 math 模組

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.12) :  100.12
math.fabs(100.72) :  100.72
math.fabs(math.pi) :  3.141592653589793

Python3 數字 Python3 數字