python中的矩阵求逆问题:(A)⁻ⁱA.≠ (一)

2024-04-26 21:48:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直面临一个有趣的python问题。我试过求3x3矩阵A的逆

[[1 2 3]
[4 5 6]
[7 8 9]]

然后把它乘以初始值:A⁻ⁱA.我得到的不是单位矩阵(所有对角线元素都等于1),而是:

[[ 12.   8.   8.]
 [-16.  -8.   0.]
 [  4.   0.   0.]]

只有在这种特定情况下才会出现问题。带有其他值的矩阵给出正确的结果。代码如下:

import numpy as np
np.set_printoptions(precision=2,suppress=True)

A = np.array([1,2,3,4,5,6,7,8,9])
A = A.reshape(3,3)

print(A)
print(np.linalg.det(A))
print(np.matmul(np.linalg.inv(A),A))

输出:

[[1 2 3]
 [4 5 6]
 [7 8 9]]

6.66133814775094e-16

[[ 12.   8.   8.]
 [-16.  -8.   0.]
 [  4.   0.   0.]] 

Tags: 代码importnumpy元素asnp情况矩阵
3条回答

这个矩阵的行列式是0。自

import numpy as np
np.set_printoptions(precision=2,suppress=True)

A = np.array([1,2,3,4,5,6,7,8,9])
A = A.reshape(3,3)
# print determinant
print(np.linalg.det(A))

返回

[[1 2 3]
 [4 5 6]
 [7 8 9]]
0.0

你有一个没有可计算逆的矩阵

正如其他人所指出的,奇异矩阵是不可逆的,所以从a^-1A得到的答案是无意义的

Numpy包含一个方便的函数来检查condition number

np.linalg.cond(A)
# 5.0522794445385096e+16

正如维基百科所述,这是对b中的输出值Ax = bA中矩阵值的微小变化的敏感性的度量(有点像广义导数)。较大的值表示A是“il调节的”,可能导致不稳定的值。这是实值矩阵的固有特性,但浮点运算会使其恶化

cond比查看np.linalg.det(A)更有用,因为它对A中的值比例不敏感(而范数和行列式是)。例如,这里是一个值很小的矩阵,但实际上不存在可逆性问题:

A = 1e-10*np.random.random(size=(3,3))

np.linalg.det(A)
# 2.128774239739163e-31
# ^^ this looks really bad...

np.linalg.cond(A)
# 8.798791503909136
# nevermind, it's probably ok

A_ident = np.matmul(np.linalg.inv(A), A)
np.linalg.norm(A_ident - np.identity(3))
# 5.392490230798587e-16
# A^(-1)*A is very close to the identity matrix, not il-conditioned.

你的矩阵是不可逆的,比如wolfram alpha,它说矩阵是奇异的

Python打印了一个非零值的行列式(6.66133814775094e-16),但是,这个值非常接近于0,所以您应该这样对待它。计算机对浮点数所做的运算通常不是完全精确的(例如,见问题Why are floating point numbers inaccurate?),这可能是行列式的值接近于零的原因,但并不完全如此

相关问题 更多 >