21

I am working with Python 3.6.
I am really confused, why this happened ?

In [1]: import numpy as np

In [2]: a = np.array(-1)

In [3]: a
Out[3]: array(-1)

In [4]: a ** (1/3)
/Users/wonderful/anaconda/bin/ipython:1: RuntimeWarning: invalid        value encountered in power
  #!/Users/wonderful/anaconda/bin/python
Out[4]: nan
Naive
  • 475
  • 1
  • 6
  • 14
  • For one numpy does not consider 0d arrays as scalars. https://stackoverflow.com/questions/773030/why-are-0d-arrays-in-numpy-not-considered-scalar – Pax Vobiscum Jul 29 '17 at 02:27

2 Answers2

41

Numpy does not seem to allow fractional powers of negative numbers, even if the power would not result in a complex number. (I actually had this same problem earlier today, unrelatedly). One workaround is to use

np.sign(a) * (np.abs(a)) ** (1 / 3)
Kevin
  • 726
  • 8
  • 11
  • 1
    Yeah I like the answer this code generates better. So much simpler than having to deal with floating point error. – Back2Basics Jul 29 '17 at 02:52
12

change the dtype to complex numbers

a = np.array(-1, dtype=np.complex128)

The problem arises when you are working with roots of negative numbers.

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
Back2Basics
  • 7,406
  • 2
  • 32
  • 45
  • 2
    In [5]: a = np.array(-1, dtype=np.complex) In [6]: a ** (1/3) Out[6]: (0.50000000000000011+0.8660254037844386j) – Naive Jul 29 '17 at 03:17