Last active
January 12, 2022 17:27
-
-
Save ekralc/269be1c619f2350195f3b651368d3892 to your computer and use it in GitHub Desktop.
Python implementation of Gaussian elimination using row pivoting.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import numpy as np | |
| def gaussian_elimination_pivot(A, b): | |
| """ | |
| Converts a normal linear system of equations to upper triangular form | |
| A is a non-singular n x n matrix containing coefficients | |
| b is an n-vector containing the values | |
| """ | |
| n = len(b) | |
| A = A.astype(float) | |
| b = b.astype(float) | |
| for i in range(n-1): | |
| dominant_row = i | |
| largest = np.abs(A[dominant_row][i]) | |
| # Find row between i and n with the largest element in the ith column | |
| for x in range(i, n): | |
| magnitude = np.abs(A[x][i]) | |
| if (magnitude > largest): | |
| largest = magnitude | |
| dominant_row = x | |
| # Swap i and dominant_row | |
| if i != dominant_row: | |
| A[[i, dominant_row]] = A[[dominant_row, i]] | |
| b[i], b[dominant_row] = b[dominant_row], b[i].copy() | |
| for j in range(i + 1, n): | |
| multiplier = A[j][i] / A[i][i] | |
| A[j] -= multiplier * A[i] | |
| b[j] -= multiplier * b[i] | |
| # Explicitly set this to 0 to avoid rounding errors | |
| A[j, i] = 0.0 | |
| return A, b |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment