Search code examples
pythonpython-3.xmathpython-3.7

Cube root in python different in shell


I noticed that when I run this program:

from random import *
z=random()*-1
print(z)
print(z**(1/3))

It returns a complex value. For example, one time its output was

-0.08310434620988971
(0.21819489400101133+0.37792464236185713j)

However, if I run the equivalent command in the shell, it returns the correct answer: enter image description here

I have repeated this experiment several times, with the same result. Does anybody know why this is?


Solution

  • Exponentiation has a higher precedence to sign. While -0.08310434620988971**(1/3) is actually

    -(0.08310434620988971**(1/3))
    

    z**(1/3) calculates

    (-0.08310434620988971)**(1/3)
    

    In the second example z is already a negative number, so the result in that context is correct.