Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to raise an array of numbers to a power with NumPy?

NumPy has log, log2, and log10 methods which can perform vectorized log base e / 2 / 10 (respectively). However, for doing the inverse operation (exponentiation), I only see exp. Why is there no exp2 / exp10 / etc?

I've tried using np.power(10, nums), but it won't let me raise to a negative power. 10 ** nums does not work either.

like image 344
James Ko Avatar asked Sep 17 '25 07:09

James Ko


1 Answers

It should work fine with 10 ** nums provided you use the float dtype. Otherwise it will create an integer array:

>>> a = numpy.array([-1, 0, 1, 2, 3], dtype=int)
>>> 2 ** a
array([0, 1, 2, 4, 8])
>>> 10 ** a
array([   0,    1,   10,  100, 1000])
>>> a = numpy.array([-1, 0, 1, 2, 3], dtype=float)
>>> 10 ** a
array([  1.00000000e-01,   1.00000000e+00,   1.00000000e+01,
         1.00000000e+02,   1.00000000e+03])

You can also coerce to float by using 10.0 instead of 10:

>>> a = numpy.array([-1, 0, 1, 2, 3], dtype=int)
>>> 10.0 ** a
array([  1.00000000e-01,   1.00000000e+00,   1.00000000e+01,
         1.00000000e+02,   1.00000000e+03])
like image 199
Oscar Benjamin Avatar answered Sep 19 '25 20:09

Oscar Benjamin