Description

1. Set up initial matrix element by element

2. Read the Augmented Matrix (A) of n by n+1 Size

3. Transform Augmented Matrix (A) to Upper Triangular Matrix using Row Operations

4. Obtain Solution using Back Substitution

5. Display Result

Code

 1 import numpy as np
 2 import sys
 3 
 4 # Set up the initial matrix
 5 n = int(input('Enter number of unknowns: '))
 6 a = np.zeros((n,n+1))
 7 x = np.zeros(n)
 8 
 9 # Input the coefficients of the augmented matrix
10 print('Enter coefficients:')
11 for i in range(n):
12     for j in range(n+1):
13         a[i][j] = float(input( 'a['+str(i)+']['+ str(j)+']='))
14 
15 # Applying the elimination method (方程术)
16 for i in range(n):
17     if a[i][i] == 0.0:
18         sys.exit('Divide by zero detected!')
19         
20     for j in range(i+1, n):
21         ratio = a[j][i]/a[i][i]
22         
23         for k in range(n+1):
24             a[j][k] = a[j][k] - ratio * a[i][k]
25 
26 # Back Substitution
27 x[n-1] = a[n-1][n]/a[n-1][n-1]
28 
29 for i in range(n-2,-1,-1):
30     x[i] = a[i][n]
31     
32     for j in range(i+1,n):
33         x[i] = x[i] - a[i][j]*x[j]
34     
35     x[i] = x[i]/a[i][i]
36 
37 # Display solution
38 print('\nThe solution is: ')
39 for i in range(n):
40     print('x%d = %0.2f' %(i,x[i]), end = '\t')

Example and Results

Solve the linear system:

Enter number of unknowns: 4
Enter coefficients:

a[0][0]=5
a[0][1]=4
a[0][2]=3
a[0][3]=2
a[0][4]=1496
a[1][0]=4
a[1][1]=2
a[1][2]=6
a[1][3]=3
a[1][4]=1175
a[2][0]=3
a[2][1]=1
a[2][2]=7
a[2][3]=5
a[2][4]=958
a[3][0]=2
a[3][1]=3
a[3][2]=5
a[3][3]=1
a[3][4]=861

The solution is: 
x0 = 177.00     x1 = 121.00     x2 = 23.00      x3 = 29.00


Forward-elimination-method.jpg
Community content is available under CC-BY-SA unless otherwise noted.