How to get the real cube root of a negative number in Python3?

前端 未结 2 1843
北荒
北荒 2020-12-21 01:20

Python 3.4 seemingly randomly decides whether it returns the real or complex root of a number using the ** operator:

>>> (863.719-250         


        
相关标签:
2条回答
  • 2020-12-21 01:36

    In the second case actually the cube root is getting evaluated first then the minus sign is getting applied, hence the real root.

    That is -1636.281**(1/3) becomes -(1636.281**(1/3)) . And you can use a similar logic to get the real cubic roots as well.

    But actually, when doing cubic root of negative numbers you always get complex numbers in python.

    >>> -1636.281**(1/3)  
    -11.783816270504108
    >>> (-1636.281)**(1/3)
    (5.891908135252055+10.205084243784958j)
    

    If you want real numbers you can add code like -

    def cube(x):
        if x >= 0:
            return x**(1/3)
        elif x < 0:
            return -(abs(x)**(1/3))
    
    0 讨论(0)
  • 2020-12-21 01:40

    https://docs.python.org/3/reference/expressions.html#the-power-operator

    In an unparenthesized sequence of power and unary operators, the operators are evaluated from right to left (this does not constrain the evaluation order for the operands): -1**2 results in -1.

    So your expression

    -1636.281**(1/3)
    

    is actually evaluated as

    -(1636.281**(1/3))
    
    0 讨论(0)
提交回复
热议问题