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

前端 未结 2 1848
北荒
北荒 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))
    

提交回复
热议问题