Skip to content

Commit 688480f

Browse files
authored
Gaussian Elimination
A function to to solve for x in the matrix equation Ax = b,
1 parent f581e7e commit 688480f

1 file changed

Lines changed: 60 additions & 0 deletions

File tree

Gaussian Elimination

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
# The 'gauss' function takes two matrices, 'a' and 'b', with 'a' square, and it return the determinant of 'a' and a matrix 'x' such that a*x = b.
2+
# If 'b' is the identity, then 'x' is the inverse of 'a'.
3+
4+
import copy
5+
from fractions import Fraction
6+
7+
def gauss(a, b):
8+
a = copy.deepcopy(a)
9+
b = copy.deepcopy(b)
10+
n = len(a)
11+
p = len(b[0])
12+
det = 1
13+
for i in range(n - 1):
14+
k = i
15+
for j in range(i + 1, n):
16+
if abs(a[j][i]) > abs(a[k][i]):
17+
k = j
18+
if k != i:
19+
a[i], a[k] = a[k], a[i]
20+
b[i], b[k] = b[k], b[i]
21+
det = -det
22+
23+
for j in range(i + 1, n):
24+
t = a[j][i]/a[i][i]
25+
for k in range(i + 1, n):
26+
a[j][k] -= t*a[i][k]
27+
for k in range(p):
28+
b[j][k] -= t*b[i][k]
29+
30+
for i in range(n - 1, -1, -1):
31+
for j in range(i + 1, n):
32+
t = a[i][j]
33+
for k in range(p):
34+
b[i][k] -= t*b[j][k]
35+
t = 1/a[i][i]
36+
det *= a[i][i]
37+
for j in range(p):
38+
b[i][j] *= t
39+
return det, b
40+
41+
def zeromat(p, q):
42+
return [[0]*q for i in range(p)]
43+
44+
def matmul(a, b):
45+
n, p = len(a), len(a[0])
46+
p1, q = len(b), len(b[0])
47+
if p != p1:
48+
raise ValueError("Incompatible dimensions")
49+
c = zeromat(n, q)
50+
for i in range(n):
51+
for j in range(q):
52+
c[i][j] = sum(a[i][k]*b[k][j] for k in range(p))
53+
return c
54+
55+
56+
def mapmat(f, a):
57+
return [list(map(f, v)) for v in a]
58+
59+
def ratmat(a):
60+
return mapmat(Fraction, a)

0 commit comments

Comments
 (0)