python math.fabs()方法的作用
math.fabs()方法
如果使用python内置函数abs()将返回一个数的绝对值,与该函数不同的是,python math module中的fabs()也可以返回一个数的绝对值,fabs()是以浮点数float类型的值进行返回。
fabs()语法
fabs(x, /)
python源码中对fabs()方法的介绍:
Return the absolute value of the float x.
参数
参数 | 描述 |
---|---|
x | 必须参数,real number,如果传入的不是数值,python将抛出TypeError |
返回值
参数的绝对值,python的浮点数float类型。
math.fabs()实例代码
>>> import math
>>> math.fabs(-1)
1.0
>>> math.fabs() #fabs()必须传递一个参数
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: fabs() takes exactly one argument (0 given)
>>> math.fabs(0)
0.0
>>> math.fabs('-1') #参数必须为real number
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: must be real number, not str