Google-Foobar/3.b. doomsday-fuel (failed)/inverse.py
2024-04-16 02:50:37 -07:00

121 lines
3.2 KiB
Python

def getInverse(self):
n = len(self.matrix)
AM = copy_matrix(self.getMatrix)
I = self.I
IM = copy_matrix(self.I)
indices = list(range(n))
for fd in range(n):
fdScaler = 1.0 / AM[fd][fd]
for j in range(n):
AM[fd][j] *= fdScaler
IM[fd][j] *= fdScaler
for i in indices[0:fd] + indices[fd+1:]:
crScaler = AM[i][fd]
for j in range(n):
AM[i][j] = AM[i][j] - crScaler * AM[fd][j]
IM[i][j] = IM[i][j] - crScaler * IM[fd][j]
return IM
# -----------------------------------------------
def eliminate(r1, r2, col, target=0):
fac = (r2[col]-target) / r1[col]
for i in range(len(r2)):
r2[i] -= fac * r1[i]
def gauss(a):
for i in range(len(a)):
if a[i][i] == 0:
for j in range(i+1, len(a)):
if a[i][j] != 0:
a[i], a[j] = a[j], a[i]
break
else:
print("MATRIX NOT INVERTIBLE")
return -1
for j in range(i+1, len(a)):
eliminate(a[i], a[j], i)
for i in range(len(a)-1, -1, -1):
for j in range(i-1, -1, -1):
eliminate(a[i], a[j], i)
for i in range(len(a)):
eliminate(a[i], a[i], i, target=1)
return a
def inverse(a):
tmp = [[] for _ in a]
for i,row in enumerate(a):
assert len(row) == len(a)
tmp[i].extend(row + [0]*i + [1] + [0]*(len(a)-i-1))
gauss(tmp)
ret = []
for i in range(len(tmp)):
ret.append(tmp[i][len(tmp[i])//2:])
return ret
# -----------------------------------------------
def invert_matrix(AM, IM):
for fd in range(len(AM)):
fdScaler = 1.0 / AM[fd][fd]
for j in range(len(AM)):
AM[fd][j] *= fdScaler
IM[fd][j] *= fdScaler
for i in list(range(len(AM)))[0:fd] + list(range(len(AM)))[fd+1:]:
crScaler = AM[i][fd]
for j in range(len(AM)):
AM[i][j] = AM[i][j] - crScaler * AM[fd][j]
IM[i][j] = IM[i][j] - crScaler * IM[fd][j]
return IM
def identity_matrix(n):
I = zeros_matrix(n, n)
for i in range(n):
I[i][i] = 1.0
return I
def copy_matrix(m):
print m
rows = len(m)
cols = len(m[0])
mc = []
while len(mc) < rows:
mc.append([])
while len(mc[-1]) < cols:
mc[-1].append(0.0)
for i in range(rows):
for j in range(rows):
mc[i][j] = m[i][j]
return mc
def zeros_matrix(rows, cols):
"""
Creates a matrix filled with zeros.
:param rows: the number of rows the matrix should have
:param cols: the number of columns the matrix should have
:returns: list of lists that form the matrix.
"""
M = []
while len(M) < rows:
M.append([])
while len(M[-1]) < cols:
M[-1].append(0.0)
return M
m = [
[1,.5],
[-0.44444,1]
]
def print2D(array):
for arr in array:
print arr
return ""
print2D(inverse(m))
print2D(invert_matrix(m, identity_matrix(2)))