What I want to do: Implement in Python how to find the inverse matrix
When the size of the matrix becomes large, we have to think about optimization of processing, but
In this article, we aim to combine the "conceptual part of finding the inverse matrix" with the Python implementation.
(Use Numpy
)
A=\left(
\begin{matrix}
1 & 2 \\
3 & 4
\end{matrix}
\right)
will do. In the implementation it looks like this:
> import numpy as np
> A = np.array([[1,2],[3,4]])
> A
array([[1, 2],
[3, 4]])
If the determinant = 0, check because there is no inverse matrix or hesitation:
{\rm det}(A)={\rm det}\left(
\begin{matrix}
1 & 2 \\
3 & 4
\end{matrix}
\right)
=1\times 4-2\times3=-2
In terms of implementation
> np.linalg.det(A)
-2.0000000000000004
Mathematically
A = \left(
\begin{matrix}
a & b \\
c & d
\end{matrix}\right)
Against
A^{-1} = \frac{1}{{\rm det}A}\left(
\begin{matrix}
d & -b \\
-c & a
\end{matrix}\right)
Substitute as known.
A^{-1} = \frac{1}{-2}\left(
\begin{matrix}
4 & -2 \\
-3 & 1
\end{matrix}\right)
=\left(
\begin{matrix}
-2 & 1 \\
1.5 & -0.5
\end{matrix}
\right)
In terms of implementation
> inv_A = np.linalg.inv(A)
> inv_A
array([[-2. , 1. ],
[ 1.5, -0.5]])
Where linalg
is a module of numpy
. For more details
http://docs.scipy.org/doc/numpy/reference/routines.linalg.html
See
The confirmation of the story, that is, that multiplying the inverse matrix and the original matrix gives an identity matrix, isn't it?
AA^{-1}=A^{-1}A=
\left(
\begin{matrix}
1 & 0 \\
0 & 1
\end{matrix}
\right)
> np.dot(A,inv_A)
array([[ 1.00000000e+00, 1.11022302e-16],
[ 0.00000000e+00, 1.00000000e+00]])
> np.dot(inv_A,A)
array([[ 1.00000000e+00, 4.44089210e-16],
[ 0.00000000e+00, 1.00000000e+00]])
It's a numerical thing that doesn't become a unit matrix beautifully, I'm not sure, but ...
If you want to experiment, try experimenting with different matrices $ A $.
Recommended Posts