Python fabs()方法示例| Python数学函数

Python fabs()是一个内置的数学函数,用于获取数字的绝对值。它首先找到绝对值,然后将数字转换为浮点型数字,而不管给定的数字是整数还是浮点型。 fabs()方法位于Python中的数学库下,这意味着我们必须首先导入数学才能使用此方法。

Python fabs()方法

内容概述

  • 1 Python fabs()方法
  • 2 Python中fabs()和abs()之间的区别
  • 3结论
  • 4另请参见

Python fabs()函数是Math函数之一,该函数返回特定表达式或特定数字的绝对值((正值))。

句法

math.fabs(number)

fabs()方法采用一个参数,即将返回其绝对值的数字。

number:可以是您要在Python中找到绝对值的数字或有效的数字表达式。

  • 如果number参数为正数或负数,则fabs()函数将返回绝对值。
  • 如果数字参数不是数字,则fabs()函数将返回TypeError。

返回值

该方法返回给定数字的绝对值,并以浮点型返回。

编程范例

import math
# Take two integer from user
num1 = float(input("Enter a float number: "))
num2 = int(input("Enter an integer: "))

# Now we will check what happens when we call fabs()
print("Absolute value of float number is: ", math.fabs(num1))
print("Absolute value of integer is: ", math.fabs(num2))

# Sum of these two number
sum1 = num1+float(num2)
# Printing sum and absolute sum
print("Sum is: ", sum1)
print("Absolute value of sum is: ", math.fabs(sum1))

输出量

Enter a float number: -26.4
Enter an integer: 12
Absolute value of float number is:  26.4
Absolute value of integer is:  12.0
Sum is:  -14.399999999999999
Absolute value of sum is: 14.399999999999999

在上面的程序中,我们采用了两个输入,一个是浮点数(负),另一个是正整数。然后我们打印了它们的绝对值。

在这里我们可以看到整数(12)转换为浮点型数字。之后,我们计算了这两个数字的和。为此,我们首先将整数转换为浮点数。

最后,我们打印了总和的绝对值。

例子2

请参阅以下编程。

# app.py

import math

Tup = (11, 21, 30, -46, 19)  # Tuple Declaration
Lis = [-11, 22, -3.3, -44, 55]  # List Declaration

print('Absolute value of Positive Number = %.2f' % math.fabs(10))
print('Absolute value of Negative Number = %.2f' % math.fabs(-15))

print('Absolute value of Tuple Item = %.2f' % math.fabs(Tup[3]))
print('Absolute value of List Item = %.2f' % math.fabs(Lis[2]))

print('Absolute value of Multiple Number = %.2f' % math.fabs(10 + 20 - 40))
print('Absolute value of String Number = ', math.fabs('AppDividend'))

输出量

python3 app.py
Absolute value of Positive Number = 11.00
Absolute value of Negative Number = 19.00
Absolute value of Tuple Item = 46.00
Absolute value of List Item = 3.30
Absolute value of Multiple Number = 10.00
Traceback (most recent call last):
  File "app.py", line 13, in 
    print('Absolute value of String Number = ', math.fabs('AppDividend'))
TypeError: must be real number, not str

在上面的示例中,我们使用了字符串,元组和列表。

对于字符串,它返回TypeError,因为我们需要一个作为整数的参数。

Python中fabs()和abs()之间的区别

Abs()和fabs()函数均用于查找数字的绝对值。两者都将返回数字的绝对值。

区别在于,即使参数为整数,math.fabs(number)也会始终返回浮点数。相反,Python abs()将根据参数返回浮点数或整数。

如果参数是复数,则abs()将返回幅度部分,而fabs()将返回错误。

结论

即使自变量是整数,Python math.fabs(number)也会始终返回浮点数,如果您传递复数或其他数字,则它将返回错误。

也可以看看

Python数学copysign()

Python数学函数

Python math.sqrt()

Python math.floor()

资讯来源:由0x资讯编译自APPDIVIDEND,版权归作者Ankit Lathiya所有,未经许可,不得转载
你可能还喜欢