Skip to content

Instantly share code, notes, and snippets.

@j9ac9k
Last active July 9, 2023 01:52
Show Gist options
  • Save j9ac9k/6b5cd12aa9d2e5aa861f942b786293b4 to your computer and use it in GitHub Desktop.
Save j9ac9k/6b5cd12aa9d2e5aa861f942b786293b4 to your computer and use it in GitHub Desktop.
Gaussian Elimination in Python
def gauss(A):
m = len(A)
assert all([len(row) == m + 1 for row in A[1:]]), "Matrix rows have non-uniform length"
n = m + 1
for k in range(m):
pivots = [abs(A[i][k]) for i in range(k, m)]
i_max = pivots.index(max(pivots)) + k
# Check for singular matrix
assert A[i_max][k] != 0, "Matrix is singular!"
# Swap rows
A[k], A[i_max] = A[i_max], A[k]
for i in range(k + 1, m):
f = A[i][k] / A[k][k]
for j in range(k + 1, n):
A[i][j] -= A[k][j] * f
# Fill lower triangular matrix with zeros:
A[i][k] = 0
# Solve equation Ax=b for an upper triangular matrix A
x = []
for i in range(m - 1, -1, -1):
x.insert(0, A[i][m] / A[i][i])
for k in range(i - 1, -1, -1):
A[k][m] -= A[k][i] * x[0]
return x
@nopeva
Copy link

nopeva commented Jul 28, 2021

hi , thank you for code but I could not do this which is for 4 or more unknown equations . could you help me ?

Haven't touched this in ages, can you provide a working example? This has handled arbitrary sized equations.

Thanks for the code. I am having trouble with singular matrices when using it with bigger matrices and have found the following article which deals with this specific problem for gaussian elimination. It seems to be an easy extension, I wonder if you could give help me with it given I am not familiar with the method: "When a row of zeros, say the ith, is encountered in the transform of A, the diagonal element of that row is changed to 1, and in the augmented portion of the matrix all other rows are changed to 0, the ith row being unchanged".

@fezedimma
Copy link

how would i write a program that does forward elimination - use the naive method for python code

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment