python中的矩阵求逆稍微有点不正确
我试着用这个算法来反转一个nxn矩阵 我在这个矩阵上运行了这个函数python中的矩阵求逆稍微有点不正确,python,matrix,linear-algebra,matrix-inverse,Python,Matrix,Linear Algebra,Matrix Inverse,我试着用这个算法来反转一个nxn矩阵 我在这个矩阵上运行了这个函数 [[1.0, -0.5], [-0.4444444444444444, 1.0]] 并且得到了输出 [[ 1.36734694, 0.64285714] [ 0.57142857, 1.28571429]] 正确的输出意味着 [[ 1.28571429, 0.64285714] [ 0.57142857, 1.28571429]] 我的功能: def inverse(m): n = len(m)
[[1.0, -0.5],
[-0.4444444444444444, 1.0]]
并且得到了输出
[[ 1.36734694, 0.64285714]
[ 0.57142857, 1.28571429]]
正确的输出意味着
[[ 1.28571429, 0.64285714]
[ 0.57142857, 1.28571429]]
我的功能:
def inverse(m):
n = len(m)
P = -1
D = 1
mI = m
while True:
P += 1
if m[P][P] == 0:
raise Exception("Not Invertible")
else:
D = D * m[P][P]
for j in range(n):
if j != P:
mI[P][j] = m[P][j] / m[P][P]
for i in range(n):
if i != P:
mI[i][P] = -m[i][P] / m[P][P]
for i in range(n):
for j in range(n):
if i != P and j != P:
mI[i][j] = m[i][j] + (m[P][j] * mI[i][P])
mI[P][P] = 1 / m[P][P]
if P == n - 1: # All elements have been looped through
break
return mI
我在哪里犯错误?
输出
逆:[[十进制('1.285714285714285693893862813'),
十进制('0.6428571428571428469469314065'),
[十进制('0.5714285714285713877877256260'),
十进制('1.285714285714285693893862813')]]
numpy:[[1.28571429 0.64285714][0.57142857 1.28571429]]
我的思考过程:
起初,我认为可能存在潜在的浮点舍入错误。事实证明并非如此。这就是十进制爵士乐的作用
你的虫子在这里
mI = m # this just creates a pointer that points to the SAME list as m
这里呢
for i in range(n):
for j in range(n):
if i != P and j != P:
mI[i][j] = m[i][j] + (m[P][j] * mI[i][P])
mI[P][P] = 1 / m[P][P]
# you are not copying mI to m for the next iteration
# you are also not zeroing mI
if P == n - 1: # All elements have been looped through
break
return mI
根据该算法,每次迭代都会创建一个新的a矩阵,它不会继续修改相同的旧a矩阵。我推断这意味着在循环不变量中,a变成了。适用于您的测试用例,结果证明是正确的。您可能对此感兴趣:@cᴏʟᴅsᴘᴇᴇᴅ 谢谢你的链接。我真的看到了,但我正在努力让这个算法工作。我喜欢这本书的简短之处。你在实现什么反演算法?@cᴏʟᴅsᴘᴇᴇᴅ 我的问题中有一个链接啊,没有看到。我的错。小心用python制作容器的引用副本!
for i in range(n):
for j in range(n):
if i != P and j != P:
mI[i][j] = m[i][j] + (m[P][j] * mI[i][P])
mI[P][P] = 1 / m[P][P]
# you are not copying mI to m for the next iteration
# you are also not zeroing mI
if P == n - 1: # All elements have been looped through
break
return mI