Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Raise to 1/3 gives complex number

Tags:

python

numpy

I cannot understand the following output. I would expect Numpy to return -10 (or an approximation). Why is it a complex number?

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

Numpy answer

(5+8.660254037844384j)

Numpy official tutorial says the answer is nan. You can find it in the middle of this tutorial.

like image 325
user1700890 Avatar asked Jul 05 '15 13:07

user1700890


People also ask

What is i3 equal to?

Answer and Explanation: The value of i3 is -i. We can determine this by multiplying i, or √−1 , by itself three times. We see that i3 = -i.

How do you find a complex number?

A complex number is the sum of a real number and an imaginary number. A complex number is expressed in standard form when written a+bi where a is the real part and bi is the imaginary part. For example, 5+2i is a complex number. So, too, is 3+4√3i.

What happens when you raise a number to the power of i?

It is a rather curious fact that i raised to the i-th power is actually a real number! In fact, its value is approximately 0.20788.


1 Answers

You are exponentiating a regular Python scalar rather than a numpy array.

Try this:

import numpy as np

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

The 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 = -1000
print(np.copysign(np.abs(x) ** (1. / 3), x))
# -10.0

Update 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.0

Update 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.

like image 151
ali_m Avatar answered Oct 23 '22 08:10

ali_m