I have a simple matrix in Python:
[[1134.01 0. ]
[ 0. 1134.01]]
And I need to raise it to the power of -1. I have tried
mat**-1 and mat = pow(mat, -1)
Both methods give me an infinity in the 0 place (I get it you can't divide by zero). The result looks like:
[[0.00088183 inf]
[ inf 0.00088183]]
And it gives me this warning because it is trying to divide by zero:
RuntimeWarning: divide by zero encountered in reciprocal
So other than manually replacing the inf with 0 or adding a small value to my original matrix, is there a way to tell python not to produce the inf and put a 0 instead?
CodePudding user response:
You can pass a where
attribute to np.power
to avoid calculating over zero:
a = np.array([
[1134.01, 0.],
[0., 1134.01]
])
np.power(a, -1, where=a != 0)
Which gives:
array([[0.00088183, 0. ],
[0. , 0.00088183]])
CodePudding user response:
You can use numpy.linalg.inv
instead.
>>> np.linalg.inv(np.array([[1134.01, 0], [0, 1134.01]]))
array([[0.00088183, 0. ],
[0. , 0.00088183]])