Python - abs vs fabs

前端 未结 4 689
无人共我
无人共我 2021-01-30 07:44

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

First

abs(-5)

Second

4条回答
  •  温柔的废话
    2021-01-30 08:36

    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().

提交回复
热议问题