#58 · Linear Algebra · Medium
⊣ Solve on deep-ml.comImplement Gaussian elimination with back-substitution to solve a system of linear equations Ax = b. Transform the augmented matrix to upper triangular form, then solve by back-substitution.
import numpy as np
def gaussian_elimination(A, b):
A = np.array(A, dtype=np.float64)
b = np.array(b, dtype=np.float64).reshape(-1, 1)
n = A.shape[0]
# Augmented matrix
aug = np.hstack([A, b])
# Forward elimination with partial pivoting
for col in range(n):
# Find pivot
max_row = col
for row in range(col + 1, n):
if abs(aug[row, col]) > abs(aug[max_row, col]):
max_row = row
aug[[col, max_row]] = aug[[max_row, col]]
if abs(aug[col, col]) < 1e-12:
continue
for row in range(col + 1, n):
factor = aug[row, col] / aug[col, col]
aug[row, col:] -= factor * aug[col, col:]
# Back-substitution
x = np.zeros(n)
for i in range(n - 1, -1, -1):
x[i] = aug[i, n]
for j in range(i + 1, n):
x[i] -= aug[i, j] * x[j]
x[i] /= aug[i, i]
return x.tolist()[A | b].