Gauss Elimination Method
import numpy as np
def gauss_elimination_with_custom_pivot(A, b):
# Form augmented matrix
aug = [Link](([Link](float), [Link](-1, 1).astype(float)))
n = len(b)
print("Initial Augmented Matrix:")
print(aug, "\n")
# Forward elimination
for k in range(n-1):
# --- Step 1: Handle zero pivot or try to bring '1' into pivot position ---
if aug[k, k] != 1:
swapped = False
# First preference: find a row with pivot = 1
for i in range(k+1, n):
if aug[i, k] == 1:
print(f"Row {k+1} <-> Row {i+1} (bring 1 into pivot position)")
aug[[k, i]] = aug[[i, k]]
print(aug, "\n")
swapped = True
break
# If pivot is zero, swap with first non-zero entry
if not swapped and aug[k, k] == 0:
for i in range(k+1, n):
if aug[i, k] != 0:
print(f"Row {k+1} <-> Row {i+1} (pivot was 0, swap to get nonzero)")
aug[[k, i]] = aug[[i, k]]
print(aug, "\n")
swapped = True
break
# Normalize pivot row if still not 1
pivot = aug[k, k]
if pivot != 1 and pivot != 0:
print(f"Row {k+1} -> Row {k+1} / {pivot} (normalize pivot to 1)")
aug[k, :] = aug[k, :] / pivot
print(aug, "\n")
# --- Step 2: Eliminate entries below pivot ---
for i in range(k+1, n):
if aug[i, k] != 0:
factor = aug[i, k]
print(f"Row {i+1} -> Row {i+1} - ({factor})*Row {k+1}")
aug[i, :] = aug[i, :] - factor * aug[k, :]
print(aug, "\n")
# --- Normalize last pivot row if needed ---
pivot = aug[n-1, n-1]
if pivot != 1 and pivot != 0:
print(f"Row {n} -> Row {n} / {pivot} (normalize pivot to 1)")
aug[n-1, :] = aug[n-1, :] / pivot
print(aug, "\n")
print("Row Echelon Form:")
print(aug, "\n")
# --- Back substitution ---
x = [Link](n)
for i in range(n-1, -1, -1):
x[i] = aug[i, -1] - [Link](aug[i, i+1:n], x[i+1:n])
print("Solution vector:", x)
return x
# Example Run
A = [Link]([
[0, 2, -1], # Notice: pivot in (1,1) = 0 to test swapping
[1, -1, 2],
[3, 1, 1]
])
b = [Link]([4, 3, 13])
gauss_elimination_with_custom_pivot(A, b)
We’ll use the example system:
which in matrix form is:
Explanation
1. import numpy as np
Importing NumPy library for matrix operations.
2. def gauss_elimination_with_custom_pivot(A, b):
Define a function that takes coefficient matrix A and RHS vector b.
3. aug = [Link](([Link](float), [Link](-1, 1).astype(float)))
Create the augmented matrix by horizontally stacking A and b.
For our example:
[Link](float) → converts all entries of A into floats.
[Link](-1,1) → reshapes b = [4,3,13] into a column vector.
[Link] → combines them.
4. n = len(b)
Number of equations = number of unknowns = 3.
5. print("Initial Augmented Matrix:")
print(aug, "\n")
Print the starting matrix.
6. Forward Elimination Loop
for k in range(n-1):
Loop over pivot positions (k=0,1 for a 3×3 system).
Step 1: Handle pivot
if aug[k, k] != 1:
swapped = False
If the pivot (diagonal element aug[k,k]) is not equal to 1, we try to fix it.
At k=0, aug[0,0] = 0.
(a) Try to bring a 1 into pivot
for i in range(k+1, n):
if aug[i, k] == 1:
print(f"Row {k+1} <-> Row {i+1} (bring 1 into pivot position)")
aug[[k, i]] = aug[[i, k]]
print(aug, "\n")
swapped = True
break
Look below pivot (rows 2 & 3) for a 1 in column 1.
Row 2 (aug[1,0] = 1) → perfect!
So we swap Row 1 and Row 2:
(b) If pivot = 0 but no 1, swap with nonzero
if not swapped and aug[k, k] == 0:
for i in range(k+1, n):
if aug[i, k] != 0:
print(f"Row {k+1} <-> Row {i+1} (pivot was 0, swap to get nonzero)")
aug[[k, i]] = aug[[i, k]]
print(aug, "\n")
swapped = True
break
Not triggered in this case because we already swapped with a row containing 1.
(c) Normalize pivot row
pivot = aug[k, k]
if pivot != 1 and pivot != 0:
print(f"Row {k+1} -> Row {k+1} / {pivot} (normalize pivot to 1)")
aug[k, :] = aug[k, :] / pivot
print(aug, "\n")
If pivot isn’t 1, divide row by pivot.
Here pivot = 1, so no change needed.
Step 2: Eliminate entries below pivot
for i in range(k+1, n):
if aug[i, k] != 0:
factor = aug[i, k]
print(f"Row {i+1} -> Row {i+1} - ({factor})*Row {k+1}")
aug[i, :] = aug[i, :] - factor * aug[k, :]
print(aug, "\n")
Now eliminate values below the pivot.
At k=0:
Row 2: already 0 in column 1 → nothing.
Row 3: aug[2,0] = 3 → eliminate:
Row3 → Row3 − 3×Row1
Next Iteration (k=1 pivot in column 2)
Pivot is aug[1,1] = 2, not 1.
Check if a row below has 1 in column 2 → Row3 has 4, not 1.
Pivot is nonzero, so divide Row2 by 2:
Row2 → Row2 / 2
Now eliminate below:
Row3 → Row3 − 4×Row2
Last pivot (k=2)
Pivot = -3. Normalize:
Row3 → Row3 / -3
Back Substitution
Now solve:
From Row3: z=1.333...
From Row2: y−0.5z=2 ⟹ y=2.667...
From Row1: x−y+2z=3 ⟹ x=2.0
Final solution:
x=2, y=2.667, z=1.333x = 2
****************************************************************
aug[[i, k]] = aug[[k, i]]
aug is the augmented matrix, stored as a NumPy 2-D array.
Example:
2. Indexing with a list of row indices
In NumPy, when you write:
aug[[i, k]]
you are selecting multiple rows of the matrix at once.
If i=0, k=1, then:
aug[[0,1]] means: “give me row 0 and row 1 (in that order).”
So it returns a new 2D array with just those rows.
Example:
aug[[0,1]]
-> [[ 1, 3, 2, 9],
[ 5, 2, 1, 12]]