Reputation: 805
This shows my numpy session. I wish to find the reciprocals of the elements of a given vector and store it in another vector. The function power in numpy is not helping.
Update This worked for me.
numpy.power(x*1.0,-1)
Code sample
import numpy
x = numpy.arange(5) + 1
print (x)
print (numpy.power(x, 2))
print (numpy.power(x, -1))
Upvotes: 1
Views: 4433
Reputation: 7517
As stated by Maciej Lach, your input method has to contain floats (otherwise output will be cast to integers by the numpy.reciprocal
method). But you can achieve it even with integers with:
1./x
(because 1.
is a float which will promote your results to floats).
Upvotes: 3
Reputation: 1691
Numpy provides a function to calculate reciprocal of the vector:
import numpy
x = numpy.arange(5) + 1
print (x)
r = numpy.reciprocal(x.astype(float))
print (r)
Which gives output:
[ 1. 2. 3. 4. 5.]
[ 1. 0.5 0.33333333 0.25 0.2 ]
Note that your input method has to contain floats, otherwise output vector will be cast to integer and you will end up with: [1 0 0 0 0]
.
Upvotes: 4