I'm very new to using Python and numpy, and for some reason it can't seem to give a correct answer to this matrix inverse. Now it's just this specific matrix, as far as I can tell, as when I use various different random matrices, all functions as normal.
[[1 2 3]
[4 5 6]
[7 8 9]]
Here's my code:
import numpy as np
a = np.array([[1,2,3],[4,5,6],[7,8,9]])
b = np.linalg.inv(a)
print(b)
and the console output is:
[[ 3.15251974e+15 -6.30503948e+15 3.15251974e+15]
[-6.30503948e+15 1.26100790e+16 -6.30503948e+15]
[ 3.15251974e+15 -6.30503948e+15 3.15251974e+15]]
All massive numbers, that are false answers. The correct answers are:
[[-11/12, 1/3, 1/12],[-1/6,1/3,-1/6,],[3/4,-1/3,1/12]]

Furthermore, if I try to determine what the np.dot(a,b) is, which should be (when rounded):
[[ 1. 0. 0.]
[-0. 1. 0.]
[ 0. 0. 1.]]
But I get:
[[ 0. 1. -0.5]
[ 0. 2. -1. ]
[ 0. 3. 2.5]]
And when I try these calculations on ANY (as far as I can tell, I've tried a dozen random ones) other matrix set, all the answers work out correct. I've also opened multiple new .ipynb files and it still doesn't function properly. So what's going on here, and how can I fix it/make sure it doesn't act this way with any other matrix set?
it appears as thought the code has an error and that the determinant of the matrix = 0 and therefore it does not have an inverse.
so i modified the last number in the numpy array of the 3x3 matrix (from a 9 to an 8) and this works.
You would need to add a check to proceed.
The check could look like this:
import numpy as np
a = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 8]])
det = np.linalg.det(a)
if det == 0:
print('determinant = 0. there is no inverse.')
else:
b = np.linalg.inv(a)
print(b)
which would return this:
[[-2.66666667 2.66666667 -1. ]
[ 3.33333333 -4.33333333 2. ]
[-1. 2. -1. ]]
Beyond the above, it would be helpful if you added what you would expect as the output of the inverse compared to what python (numpy) is producing....
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With