In: Computer Science
Gauss Jordan elimination using python for a 2d list (3x3) without using any library.
Thanks
gaus_jordon.py
def print_matrix(a, n): """ * function to print the matrix of size n """ for i in range(n): for j in range(n+1): print(a[i][j], " ", end="") print() def print_result(a, n, flag): """ * Function to print the desired result if unique solutions exists, otherwise prints no solution or infinite solutions depending upon the input given. """ print("Result is : ") if flag == 2: print("Infinite Solutions Exists") elif flag == 3: print("No Solution Exists") else : for i in range(n): print(a[i][n] / a[i][i], " ") def check_consistency(a, n, flag): """ * To check whether infinite solutions exists or no solution exists * flag == 2 for infinite solution * flag == 3 for No solution """ flag = 3 for i in range(n): sum = 0 for j in range(n): sum = sum + a[i][j] if sum == a[i][j]: flag = 2 return flag def perform_operation(a, n): """ * function to reduce matrix to reduced row echelon form. """ k = 0 flag = 0 m = 0 pro = 0 for i in range(n): if a[i][i] == 0: c = 1 while a[i + c][i] == 0 and (i + c) < n: c += 1 if (i + c) == n: flag = 1 break j = i for k in range(n+1): tmp = a[j][k] a[j][k] = a[j+c][k] a[j+c][k] = tmp for j in range(n): if i != j: pro = a[j][i] / a[i][i] for k in range(n+1): a[j][k] = a[j][k] - (a[i][k]) * pro return flag if __name__=="__main__": matrix = [ [0, 2, 1, 4], [1, 1, 2, 6], [2, 1, 1, 7] ] size = 3 flag = 0 flag = perform_operation(matrix, size) if flag == 1: flag = check_consistency(matrix, size, flag) print_matrix(matrix, size) print_result(matrix, size, flag)
Note : the example is for linear equations:
2y + z = 4 x + y + 2z = 6 2x + y + z = 7