Raise To 1/3 Gives Complex Number
Solution 1:
You are exponentiating a regular Python scalar rather than a numpy array.
Try this:
import numpy as np
print(np.array(-1000) ** (1. / 3))
# nanThe difference is that numpy does not automatically promote the result to a complex type, whereas a Python 3 scalar gets promoted to a complex value (in Python 2.7 you would just get a ValueError).
As explained in the link @jonrsharpe gave above, negative numbers have multiple cube roots. To get the root you are looking for, you could do something like this:
x = -1000print(np.copysign(np.abs(x) ** (1. / 3), x))
# -10.0Update 1
Mark Dickinson is absolutely right about the underlying cause of the problem - 1. / 3 is not exactly the same as a third because of rounding error, so x ** (1. / 3) is not quite the same thing as the cube root of x.
A better solution would be to use scipy.special.cbrt, which computes the 'exact' cube root rather than x ** (1./3):
from scipy.special import cbrt
print(cbrt(-1000))
# -10.0Update 2
It's also worth noting that versions of numpy >= 0.10.0 will have a new np.cbrt function based on the C99 cbrt function.
Post a Comment for "Raise To 1/3 Gives Complex Number"