abs(-5)
Second
import mathmath.fabs(-5)
How do these methods differ?
本文共 3803 字,大约阅读时间需要 12 分钟。
abs(-5) Second import mathmath.fabs(-5) How do these methods differ? | |||
|
59 | 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, also works with integers and complex numbers. Its return type depends on the type of its argument. In [7]: type(abs(-2))Out[7]: intIn [8]: type(abs(-2.0))Out[8]: floatIn [9]: type(abs(3+4j))Out[9]: floatIn [10]: type(math.fabs(-2))Out[10]: floatIn [11]: type(math.fabs(-2.0))Out[11]: floatIn [12]: type(math.fabs(3+4j))---------------------------------------------------------------------------TypeError Traceback (most recent call last)/home/alexei/ | |||
|
4 | 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 loopIn [2]: from math import fabsIn [3]: %timeit fabs(5)10000000 loops, best of 3: 115 ns per loopIn [4]: %timeit abs(-5)10000000 loops, best of 3: 88.3 ns per loopIn [5]: %timeit fabs(-5)10000000 loops, best of 3: 114 ns per loopIn [6]: %timeit abs(5.0)10000000 loops, best of 3: 92.5 ns per loopIn [7]: %timeit fabs(5.0)10000000 loops, best of 3: 93.2 ns per loopIn [8]: %timeit abs(-5.0)10000000 loops, best of 3: 91.8 ns per loopIn [9]: %timeit fabs(-5.0)10000000 loops, best of 3: 91 ns per loop So it seems 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 loopIn [2]: import mathIn [3]: %timeit math.fabs(-5)10000000 loops, best of 3: 194 ns per loop So | ||||||||||||||||||||
|
转载地址:http://xihbi.baihongyu.com/
abs
works with far more than just integers and floats, and the result type is not always the same as the argument, e.g.abs(3+4j)
. – May 27 '12 at 7:24fabs
taking longer due to its always-float nature and you've got the right answer! – May 27 '12 at 7:25__builtin__.abs()
be successfully applied to? – May 27 '12 at 7:31__abs__
magic method – May 27 '12 at 17:59