python - Raise to 1/3 gives complex number -


i cannot understand following output. expect numpy return -10 (or approximation). why complex number?

print((-1000)**(1/3.)) 

numpy answer

(5+8.660254037844384j) 

numpy official tutorial says answer nan. can find in middle of this tutorial.

you exponentiating regular python scalar rather numpy array.

try this:

import numpy np  print(np.array(-1000) ** (1. / 3)) # nan 

the difference numpy not automatically promote result complex type, whereas python 3 scalar gets promoted complex value (in python 2.7 valueerror).

as explained in link @jonrsharpe gave above, negative numbers have multiple cube roots. root looking for, this:

x = -1000 print(np.copysign(np.abs(x) ** (1. / 3), x)) # -10.0 

update 1

mark dickinson absolutely right underlying cause of problem - 1. / 3 not same third because of rounding error, x ** (1. / 3) not quite same thing cube root of x.

a better solution use scipy.special.cbrt, computes 'exact' cube root rather x ** (1./3):

from scipy.special import cbrt  print(cbrt(-1000)) # -10.0 

update 2

it's worth noting versions of numpy >= 0.10.0 have new np.cbrt function based on the c99 cbrt function.


Comments

Popular posts from this blog

c# - Better 64-bit byte array hash -

webrtc - Which ICE candidate am I using and why? -

php - Zend Framework / Skeleton-Application / Composer install issue -