gaussian elimination python without library

Solutions on MaxInterview for gaussian elimination python without library by the best coders in the world

showing results for - "gaussian elimination python without library"
Delphine
31 Nov 2019
1
2# Importing NumPy Library
3import numpy as np
4import sys
5
6# Reading number of unknowns
7n = int(input('Enter number of unknowns: '))
8
9# Making numpy array of n x n+1 size and initializing 
10# to zero for storing augmented matrix
11a = np.zeros((n,n+1))
12
13# Making numpy array of n size and initializing 
14# to zero for storing solution vector
15x = np.zeros(n)
16
17# Reading augmented matrix coefficients
18print('Enter Augmented Matrix Coefficients:')
19for i in range(n):
20    for j in range(n+1):
21        a[i][j] = float(input( 'a['+str(i)+']['+ str(j)+']='))
22
23# Applying Gauss Elimination
24for i in range(n):
25    if a[i][i] == 0.0:
26        sys.exit('Divide by zero detected!')
27        
28    for j in range(i+1, n):
29        ratio = a[j][i]/a[i][i]
30        
31        for k in range(n+1):
32            a[j][k] = a[j][k] - ratio * a[i][k]
33
34# Back Substitution
35x[n-1] = a[n-1][n]/a[n-1][n-1]
36
37for i in range(n-2,-1,-1):
38    x[i] = a[i][n]
39    
40    for j in range(i+1,n):
41        x[i] = x[i] - a[i][j]*x[j]
42    
43    x[i] = x[i]/a[i][i]
44
45# Displaying solution
46print('\nRequired solution is: ')
47for i in range(n):
48    print('X%d = %0.2f' %(i,x[i]), end = '\t')
49
similar questions