I'm trying to use this http://www.irma-international.org/viewtitle/41011/ algorithm to invert a nxn matrix.
I ran the function on this matrix
[[1.0, -0.5],
[-0.4444444444444444, 1.0]]
and got the output
[[ 1.36734694, 0.64285714]
[ 0.57142857, 1.28571429]]
the correct output is meant to be
[[ 1.28571429, 0.64285714]
[ 0.57142857, 1.28571429]]
My function:
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
Where am I making my mistake?