Skip to content

Commit 03e9a75

Browse files
isaacgdocclauss
authored andcommitted
Add gaussian_elimination.py for solving linear systems (#1448)
1 parent ec85cc8 commit 03e9a75

File tree

1 file changed

+83
-0
lines changed

1 file changed

+83
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
"""
2+
Gaussian elimination method for solving a system of linear equations.
3+
Gaussian elimination - https://en.wikipedia.org/wiki/Gaussian_elimination
4+
"""
5+
6+
7+
import numpy as np
8+
9+
10+
def retroactive_resolution(coefficients: np.matrix, vector: np.array) -> np.array:
11+
"""
12+
This function performs a retroactive linear system resolution
13+
for triangular matrix
14+
15+
Examples:
16+
2x1 + 2x2 - 1x3 = 5 2x1 + 2x2 = -1
17+
0x1 - 2x2 - 1x3 = -7 0x1 - 2x2 = -1
18+
0x1 + 0x2 + 5x3 = 15
19+
>>> gaussian_elimination([[2, 2, -1], [0, -2, -1], [0, 0, 5]], [[5], [-7], [15]])
20+
array([[2.],
21+
[2.],
22+
[3.]])
23+
>>> gaussian_elimination([[2, 2], [0, -2]], [[-1], [-1]])
24+
array([[-1. ],
25+
[ 0.5]])
26+
"""
27+
28+
rows, columns = np.shape(coefficients)
29+
30+
x = np.zeros((rows, 1), dtype=float)
31+
for row in reversed(range(rows)):
32+
sum = 0
33+
for col in range(row + 1, columns):
34+
sum += coefficients[row, col] * x[col]
35+
36+
x[row, 0] = (vector[row] - sum) / coefficients[row, row]
37+
38+
return x
39+
40+
41+
def gaussian_elimination(coefficients: np.matrix, vector: np.array) -> np.array:
42+
"""
43+
This function performs Gaussian elimination method
44+
45+
Examples:
46+
1x1 - 4x2 - 2x3 = -2 1x1 + 2x2 = 5
47+
5x1 + 2x2 - 2x3 = -3 5x1 + 2x2 = 5
48+
1x1 - 1x2 + 0x3 = 4
49+
>>> gaussian_elimination([[1, -4, -2], [5, 2, -2], [1, -1, 0]], [[-2], [-3], [4]])
50+
array([[ 2.3 ],
51+
[-1.7 ],
52+
[ 5.55]])
53+
>>> gaussian_elimination([[1, 2], [5, 2]], [[5], [5]])
54+
array([[0. ],
55+
[2.5]])
56+
"""
57+
# coefficients must to be a square matrix so we need to check first
58+
rows, columns = np.shape(coefficients)
59+
if rows != columns:
60+
return []
61+
62+
# augmented matrix
63+
augmented_mat = np.concatenate((coefficients, vector), axis=1)
64+
augmented_mat = augmented_mat.astype("float64")
65+
66+
# scale the matrix leaving it triangular
67+
for row in range(rows - 1):
68+
pivot = augmented_mat[row, row]
69+
for col in range(row + 1, columns):
70+
factor = augmented_mat[col, row] / pivot
71+
augmented_mat[col, :] -= factor * augmented_mat[row, :]
72+
73+
x = retroactive_resolution(
74+
augmented_mat[:, 0:columns], augmented_mat[:, columns : columns + 1]
75+
)
76+
77+
return x
78+
79+
80+
if __name__ == "__main__":
81+
import doctest
82+
83+
doctest.testmod()

0 commit comments

Comments
 (0)