导入numpy
from numpy import *
生产4*4随机数组
random.rand(4,4)
Out[12]:
array([[ 0.62906836, 0.68003924, 0.23429915, 0.33934942],
[ 0.16138277, 0.50783913, 0.81208135, 0.73155125],
[ 0.03198512, 0.06235509, 0.84971987, 0.40201476],
[ 0.60382374, 0.23330463, 0.19498809, 0.49371285]])
数组转换为矩阵
randMat = mat(random.rand(4,4))
求矩阵的逆
randMat.I Out[14]: matrix([[-1.24839656, 1.95298502, 0.13778596, -0.55000061], [ 0.47513857, -1.21734464, 1.22431076, -0.99281312], [ 1.43191954, -0.30628506, -0.22557989, 0.27913877], [ 0.33002468, -0.95613875, -0.03658288, 1.42874831]])
计算矩阵与其逆矩阵相乘的结果
randMat * invRandMat
matrix([[ 1.00000000e+00, -9.71445147e-17, 8.20198943e-17,
7.97972799e-17],
[ -8.32667268e-17, 1.00000000e+00, 9.28077060e-17,
1.11022302e-16],
[ 0.00000000e+00, -4.44089210e-16, 1.00000000e+00,
0.00000000e+00],
[ 0.00000000e+00, -1.11022302e-16, -6.93889390e-18,
1.00000000e+00]]
结果应该是单位矩阵,除了对角线元素是1,其他元素应该全是0。实际输出结果中,矩阵还留下了许多非常小的元素,这是计算机误差产生的结果,计算误差值:
myEye = randMat*invRandMat myEye - eye(4)#函数eye(4)创建4*4的单位矩阵
Out[18]: matrix([[ 0.00000000e+00, -9.71445147e-17, 8.20198943e-17, 7.97972799e-17], [ -8.32667268e-17, 0.00000000e+00, 9.28077060e-17, 1.11022302e-16], [ 0.00000000e+00, -4.44089210e-16, 2.22044605e-16, 0.00000000e+00], [ 0.00000000e+00, -1.11022302e-16, -6.93889390e-18, 2.22044605e-16]])