Python - abs vs fabs

前端 未结 4 742
无人共我
无人共我 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:37

    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/npe/ in ()
    ----> 1 type(math.fabs(3+4j))
    
    TypeError: can't convert complex to float
    

提交回复
热议问题