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