Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

numpy.power for array with negative numbers

I have a numpy array arr = np.array([-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5]).
Then how can I raise every element to the (say) 3/5'th power?

When I try something like this:

>>> np.float_power(arr, 3/5)
>>> arr**(3/5)

I always get this output:

array([       nan,        nan,        nan,        nan,        nan,
   0.        , 1.        , 1.16150873, 1.26782173, 1.34910253,
   1.4157205 ])

However, x**(3/5) should be computable for negative numbers x, as it's only the fifth root of x cubed!
I think this is because Python doesn't see 3/5 as the 'perfect fraction' 3/5, but as a real number (very) close to 0.6 (for example 0.59999999999999999).

How can I fix this issue?

like image 630
Jonas De Schouwer Avatar asked Jun 24 '26 03:06

Jonas De Schouwer


1 Answers

You should take the sign away and reinsert it later:

res = np.float_power(abs(arr), 3./5)*np.sign(arr)

[-2.6265278  -2.29739671 -1.93318204 -1.51571657 -1.  0. 1. 1.51571657  1.93318204  2.29739671  2.6265278 ]

The nth root algorithm returns positive values only. I presume the implementation in numpy is similar.

like image 95
Jacques Gaudin Avatar answered Jun 26 '26 17:06

Jacques Gaudin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!