Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

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

Is there a way to ensure you get the real root when cube rooting rather than one of the complex ones?

like image 468
Danny Roberts Avatar asked Jun 18 '15 19:06

Danny Roberts


2 Answers

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))
like image 112
Anand S Kumar Avatar answered Nov 01 '22 11:11

Anand S Kumar


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))
like image 38
dlask Avatar answered Nov 01 '22 10:11

dlask