In Python 3.6, why does a negative number to the degree of a fraction return nan when in a numpy array?

I recently started learning Python, and I went through the official QuickPart NumPy guide , which includes this example for iteration.

>>> a
array([-1000,     1, -1000,    27, -1000,   125,   216,   343,   512,   
729])
>>> for i in a:
...     print(i**(1/3.))
...
nan
1.0
nan
3.0
nan
5.0
6.0
7.0
8.0
9.0

However, if I just try to raise -1000 to power (1/3.) Outside the loop, it returns a value.

>>> -1000**(1/3.)
-9.999999999999998

With parentheses around -1000, it also returns a value.

>>> (-1000)**(1/3.)
(5+8.660254037844384j)

Why does the same action return nanin a for loop? I am using Python 3.6.3 :: Anaconda custom (64-bit). I also tried with different fractions that did not round, and this is the same. With a fraction that is rounded to 0.0, it works.

I could not find a similar question. Excuse me if I miss something very obvious.

Edit: , NumPy, RuntimeWarning: , , , . , , .

+4
2

python , . , -1000**(1/3) -(1000**(1/3)).

, (-1000)**(1/3). 10 * (-1**(1/3)), complex. , , , -, :

dtype: ,

. , , . " ". downcasting .astype(t).

, , np.int16.

, , dtype, (-1000)**(1/3), .

, dtype.


\ :

>>> a = np.array([-1000, 1], dtype=np.complex)
>>> for i in a:
...     print(i**(1/3.))
...
(5+8.66025403784j)
(1+0j)
+4

, .

 def ownpow(a, b):
        if a > 0:
            return a**b
        if a < 0:
            temp = abs(a)**b
            return -1*temp

    a= np.array([-1000,     1, -1000,    27, -1000,   125,   216,   343,   512,  729]) 

    for i in a:
        print(ownpow(i,(1/3.)))

numpy , .

0

Source: https://habr.com/ru/post/1694237/


All Articles