Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Neither builtin power function nor np.power works

Tags:

python

numpy

I've got the following simple two things given:

n = 2.01
array = np.array([-0.3700708 , -0.41282227, -0.25959961])

Now I want each of the array elements to be raised to the power of (n-1.). So I tried the following:

>>> array**(n-1.)
array([ nan,  nan,  nan])
>>> np.power(array, (n-1.))
array([ nan,  nan,  nan])

If I take out each element and raise it to the power of (n-1.), it works fine. Where's the error?

like image 527
user3017048 Avatar asked Feb 11 '23 19:02

user3017048


2 Answers

A work around - convert array to complex

In [83]: (array+0j)**(n-1)  # or array.astype('complex')
Out[83]: 
array([-0.36622949-0.01150923j, -0.40898407-0.01285284j,
       -0.25599573-0.00804499j])

Apparently the ** responds to the dtype of the array, producing complex values when the dtype is complex, but throwing up its hands in failure when it is float. Details probably can be found buried in the C code.

like image 184
hpaulj Avatar answered Feb 13 '23 09:02

hpaulj


The reason is that the results are complex values, e.g.

  -0.3700708 ** 1.01 == -0.366229 - 0.011509i

Edit: When computing the value at Wolfram Alpha do (raise negative into power)

  (-0.3700708) ** 1.01

and not (first raise into power, then negate)

  -0.3700708 ** 1.01
like image 21
Dmitry Bychenko Avatar answered Feb 13 '23 10:02

Dmitry Bychenko