python中abs和fabs的区别_Python - abs vs fabs

问题

I noticed that in python there are two similar looking methods for finding the absolute value of a number:

First

abs(-5)

Second

import math

math.fabs(-5)

How do these methods differ?

回答1:

math.fabs() converts its argument to float if it can (if it can't, it throws an exception). It then takes the absolute value, and returns the result as a float.

In addition to floats, abs() also works with integers and complex numbers. Its return type depends on the type of its argument.

In [7]: type(abs(-2))

Out[7]: int

In [8]: type(abs(-2.0))

Out[8]: float

In [9]: type(abs(3+4j))

Out[9]: float

In [10]: type(math.fabs(-2))

Out[10]: float

In [11]: type(math.fabs(-2.0))

Out[11]: float

In [12]: type(math.fabs(3+4j))

---------------------------------------------------------------------------

TypeError Traceback (most recent call last)

/home/alexei/ in ()

----> 1 type(math.fabs(3+4j))

TypeError: can't convert complex to float

回答2:

Edit: as @aix suggested, a better (more fair) way to compare the speed difference:

In [1]: %timeit abs(5)

10000000 loops, best of 3: 86.5 ns per loop

In [2]: from math import fabs

In [3]: %timeit fabs(5)

10000000 loops, best of 3: 115 ns per loop

In [4]: %timeit abs(-5)

10000000 loops, best of 3: 88.3 ns per loop

In [5]: %timeit fabs(-5)

10000000 loops, best of 3: 114 ns per loop

In [6]: %timeit abs(5.0)

10000000 loops, best of 3: 92.5 ns per loop

In [7]: %timeit fabs(5.0)

10000000 loops, best of 3: 93.2 ns per loop

In [8]: %timeit abs(-5.0)

10000000 loops, best of 3: 91.8 ns per loop

In [9]: %timeit fabs(-5.0)

10000000 loops, best of 3: 91 ns per loop

So it seems abs() only has slight speed advantage over fabs() for integers. For floats, abs() and fabs() demonstrate similar speed.

In addition to what @aix has said, one more thing to consider is the speed difference:

In [1]: %timeit abs(-5)

10000000 loops, best of 3: 102 ns per loop

In [2]: import math

In [3]: %timeit math.fabs(-5)

10000000 loops, best of 3: 194 ns per loop

So abs() is faster than math.fabs().

回答3:

math.fabs() always returns float, while abs() may return integer.

回答4:

abs() :

Returns the absolute value as per the argument i.e. if argument is int then it returns int, if argument is float it returns float.

Also it works on complex variable also i.e. abs(a+bj) also works and returns absolute value i.e.math.sqrt(((a)**2)+((b)**2)

math.fabs() :

It only works on the integer or float values. Always returns the absolute float value no matter what is the argument type(except for the complex numbers).

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值