Python 数学库的 fabs() 方法
fabs() 是Python 2 和Python 3 的数学库中指定的方法。
有时在计算两个数字之间的差异以计算一个数字与另一个数字的接近度时,我们需要找到某个数字的大小,fabs() 在我们处理整数并希望结果的情况下可以派上用场浮点数以进一步执行浮点比较,因为 fabs() 将其每个幅度转换为浮点值。
Syntax : fabs(x)
Parameters :
x : Number whose magnitude has to be computed.
Returns : Returns the magnitude of the element passed in the function. Always returns a floating point number, irrespective of the data type of the argument number.
代码 #1:演示 fabs() 工作的代码
# Python3 code to demonstrate
# the working of fabs()
# for fabs()
import math
# initializing integer
x = -2
# initializing float
y = -2.00
# printing magnitude and type of output
# type conversion to float
print("The magnitude of integer is : ", end ="")
print(math.fabs(x))
print("The type of output is : ", end ="")
print(type(math.fabs(x)))
print("\r")
# printing magnitude and type of output
print("The magnitude of float is : ", end ="")
print(math.fabs(y))
print("The type of output is : ", end ="")
print(type(math.fabs(y)))
输出 :
The magnitude of integer is : 2.0
The type of output is :
The magnitude of float is : 2.0
The type of output is :
例外 :
这个方法有很多异常,因为它总是返回一个浮点数,当Python无法将参数转换为浮点数时,这个函数会抛出异常。例如。在字符串和复数的情况下。
代码 #2:演示 fabs() 异常的代码
# Python3 code to demonstrate
# the exception of fabs()
# for fabs()
import math
# initializing string
c = "gfg"
# initializing complex number
d = 4 + 2j
# checking for exceptions
try :
print("The absolute value of string is :")
print(math.fabs(c))
except Exception as e:
print("Error !! The error on passing string is :")
print(str(e))
print("\r")
try :
print("The absolute value of complex is :")
print(math.fabs(d))
except Exception as e:
print("Error !! The error on passing complex is :")
print(str(e))
输出 :
The absolute value of string is :
Error !! The error on passing string is :
a float is required
The absolute value of complex is :
Error !! The error on passing complex is :
can't convert complex to float