Untitled
Anonymous
plain_text
02/14/2026 5:03 AM
1.4 KB
12
Indexable
# Gauss Elimination Method
def gauss_elimination(a, n):
# Forward Elimination
for i in range(n):
# Make the diagonal element non-zero
if a[i][i] == 0:
print("Pivot element is zero, cannot proceed with Gauss Elimination!")
return None
for j in range(i + 1, n):
# Calculate ratio and eliminate the variable
ratio = a[j][i] / a[i][i]
for k in range(n + 1):
a[j][k] -= ratio * a[i][k]
# Back Substitution
x = [0 for i in range(n)]
x[n - 1] = a[n - 1][n] / a[n - 1][n - 1]
for i in range(n - 2, -1, -1):
x[i] = a[i][n]
for j in range(i + 1, n):
x[i] -= a[i][j] * x[j]
x[i] /= a[i][i]
return x
# Input number of unknowns
n = int(input("Enter number of unknowns: "))
# Input the augmented matrix
print("Enter the augmented matrix (coefficients + constants):")
a = []
for i in range(n):
row = list(map(float, input(f"Enter row {i + 1}: ").split()))
a.append(row)
# Call Gauss Elimination function
solution = gauss_elimination(a, n)
if solution:
print("\nSolution:")
for i in range(n):
print(f"x{i + 1} = {solution[i]}")Editor is loading...
Leave a Comment