2020年2月6日木曜日

数学 - Python - 線形代数学 - 行列 - 行列の積 - 結合律

ラング線形代数学(上) (ちくま学現文庫)(S.ラング (著)、芹沢 正三 (翻訳)、筑摩書房)の3章(行列)、2(行列の積)、練習問題3の解答を求めてみる。

1. $\begin{array}{l}\left(AB\right)C\\ =\left[\begin{array}{cc}-1& 2\\ -2& 3\end{array}\right]\left[\begin{array}{cc}1& 4\\ 2& 3\end{array}\right]\\ =\left[\begin{array}{cc}3& 2\\ 4& 1\end{array}\right]\\ A\left(BC\right)\\ =\left[\begin{array}{cc}2& 1\\ 3& 1\end{array}\right]\left[\begin{array}{cc}1& -1\\ 1& 4\end{array}\right]\\ =\left[\begin{array}{cc}3& 2\\ 4& 1\end{array}\right]\end{array}$

2. $\begin{array}{l}\left(AB\right)C\\ =\left[\begin{array}{cc}1& 3\\ 11& 1\end{array}\right]\left[\begin{array}{c}1\\ 3\end{array}\right]\\ =\left[\begin{array}{c}10\\ 14\end{array}\right]\\ A\left(BC\right)\\ =\left[\begin{array}{ccc}2& 1& -1\\ 3& 1& 2\end{array}\right]\left[\begin{array}{c}4\\ 2\\ 0\end{array}\right]\\ =\left[\begin{array}{c}10\\ 14\end{array}\right]\end{array}$

3. $\begin{array}{l}\left(AB\right)C\\ =\left[\begin{array}{ccc}13& 7& 1\\ 0& 2& -5\end{array}\right]\left[\begin{array}{cc}1& 2\\ 3& 1\\ -1& 4\end{array}\right]\\ =\left[\begin{array}{cc}33& 37\\ 11& -18\end{array}\right]\\ A\left(BC\right)\\ =\left[\begin{array}{ccc}2& 4& 1\\ 3& 0& -1\end{array}\right]\left[\begin{array}{cc}4& 3\\ 6& 1\\ 1& 27\end{array}\right]\\ =\left[\begin{array}{cc}33& 37\\ 11& -18\end{array}\right]\end{array}$

コード

#!/usr/bin/env python3
from unittest import TestCase, main
from sympy import Matrix

print('3.')

class MyTestCase(TestCase):
def test(self):
ABCDs = [([[2, 1],
[3, 1]],
[[-1, 1],
[1, 0]],
[[1, 4],
[2, 3]],
[[3, 2],
[4, 1]]),
([[2, 1, -1],
[3, 1, 2]],
[[1, 1],
[2, 0],
[3, -1]],
[[1],
[3]],
[[10],
[14]]),
([[2, 4, 1],
[3, 0, -1]],
[[1, 1, 0],
[2, 1, -1],
[3, 1, 5]],
[[1, 2],
[3, 1],
[-1, 4]],
[[33, 37],
[11, -18]])]
for A, B, C, D in ABCDs:
A = Matrix(A)
B = Matrix(B)
C = Matrix(C)
D = Matrix(D)
self.assertEqual((A * B) * C, A * (B * C), D)

if __name__ == '__main__':
main()


% ./sample3.py -v
3.
test (__main__.MyTestCase) ... ok

----------------------------------------------------------------------
Ran 1 test in 0.042s

OK
%