Untitled

Anonymous
plain_text
02/14/2026 5:39 AM
1.6 KB
11
Indexable
#Gauss Eliination 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 Elemination!")
            return None

        for j in range(i + 1, n):
            #Calculate ratio and eleminate the variable 
            ratio = a[j][i] / a[i][i]
            for k in range(n + 1):
                a[j][k] -= ratio * a[i][k]

    # Backward 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 argumented matrix
print("Enter the argumented 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("\nSolutions:")
    for i in range(n):
        print(f"x{i + 1} = {solution[i]}")
Editor is loading...
Leave a Comment