Latest web development tutorials

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數字