Reputation: 2105
The following output from IDLE makes no sense to me.
>>> a=-1.0
>>> a**(1/3)
1.0
>>> a==-1.0
True
>>> -1.0**(1/3)
-1.0
Why are two theoretically equivalent statements returning different results? How is Python (2.7) handling the __pow__
method for doubles that this is the result? I just tried it with integers as well and received the same result. Other than computing the sign of the input to the __pow__
function and copying it to the result, how can I fix this?
Upvotes: 3
Views: 80
Reputation: 363567
This is an operator precendence issue:
>>> -1.0**(1/3)
-1.0
>>> (-1.0)**(1/3)
1.0
Also, note that (1/3)
is zero unless you import division
from the __future__
, which gives Python 3.x behavior (and a ValueError
). Use 1/3.
to get 1/3 as a float.
Upvotes: 6