LoginSignup
20
18

More than 5 years have passed since last update.

Pythonで逆行列を求める&検算

Posted at

やりたいこと:逆行列を求める方法をPythonで実装

行列のサイズが大きくなると処理の最適化とかとかを考えないといけないですが、
この記事では"逆行列を求めるっていう概念的な部分"とPythonでの実装が結びつくことを目指します。
(Numpyを使います)

(サンプル)行列の定義

A=\left(
\begin{matrix}
1 & 2 \\
3 & 4 
\end{matrix}
\right)

とします。実装ではこんな感じ:

> import numpy as np
> A = np.array([[1,2],[3,4]])

一応、中身のck

> A 
array([[1, 2],
       [3, 4]])

行列式を計算しよう

行列式=0になってしまったら、逆行列もヘッタクレもないのでチェック:

{\rm det}(A)={\rm det}\left(
\begin{matrix}
1 & 2 \\
3 & 4 
\end{matrix}
\right)
=1\times 4-2\times3=-2

実装的には

> np.linalg.det(A)
-2.0000000000000004

逆行列を求めてみよう

数学的には、

A = \left(
\begin{matrix}
a & b \\
c & d
\end{matrix}\right)

に対して

A^{-1} = \frac{1}{{\rm det}A}\left(
\begin{matrix}
d & -b \\
-c & a
\end{matrix}\right)

はわかっているものとして代入。

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)

実装的には

> inv_A = np.linalg.inv(A)
> inv_A
array([[-2. ,  1. ],
       [ 1.5, -0.5]])

ここでlinalgは、numpyのモジュール。より詳しくは
http://docs.scipy.org/doc/numpy/reference/routines.linalg.html
を参照

最後に検算

逆行列と元の行列を掛け算すると単位行列になるよね、って話の確認、つまり:

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]])

キレイに単位行列にならないのは、数値的なアレなんですかね、よく分からないんですが、、、

いろいろ試してみたい場合は、行列$A$をいろいろ変化させて実験してみて下さい。

20
18
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
20
18