'''
/* Based on Gaussian Elimination method
* for solving the n x n linear algebra system
* a11 x1+a12 x2+...+a1n xn=b1
* a21 x1+a22 x2+...+a2n xn=b2
* . . . .
* . . . .
* an1 x1+an2 x2+...+ann xn=bn
* Input number of unknowns and equations n
* with coefficent a11,a12,...,ann and b1,b2,
* ...bn. Output solution x1,x2,x3,...,xn.
*/
'''
#Gauss Elimination
print("\nEnter the no. of equations\n")
n=3
print(n)
#input the no. of equations
a= [ [0.0 for i in range(n+1)] for j in range(n+1) ] #[n][n+1],
x= [0.0 for i in range(n+1)]; # //declare an array to store the elements of augmented-matrix
print("\nEnter the elements of the augmented-matrix row-wise:\n")
a=[[-1.0 , 1.0 , 2.0 , 2.0],
[3.0 , -1.0 , 1.0, 6.0],
[-1.0 , 3.0 , 4.0 , 4.0]]
for i in range(0 ,n):
for j in range(0,n+1):
print( "a[",i,"][",j,"]=",round(a[i][j],4),'\t',end='')
print("")
# print(a) #debug
for i in range (0 , n): # //Pivotisation
for k in range (i+1 , n):
if (abs(a[i][i])<abs(a[k][i])):
for j in range (0, n+1 ) :
temp=a[i][j]
a[i][j]=a[k][j]
a[k][j]=temp
print("\nThe matrix after Pivotisation is:\n")
for i in range (0,n) : # //print the new matrix
for j in range (0, n+1) :
print( round(a[i][j],4),"\t",end='')
print("\n")
for i in range (0,n-1) : # //loop to perform the gauss elimination
for k in range (i+1,n):
t=a[k][i]/a[i][i];
for j in range (0, n +1):
a[k][j]=a[k][j]-t*a[i][j] # //make the elements below the pivot elements equal to zero or elimnate the variables
print("\n\nThe matrix after gauss-elimination is as follows:\n")
for i in range (0,n) : # //print the new matrix
for j in range(0,n+1):
print( round(a[i][j],4),"\t",end='')
print("\n")
for i in range(n-1,-1 ,-1): # //back-substitution
# //x is an array whose values correspond to the values of x,y,z..
x[i]=a[i][n]; #//make the variable to be calculated equal to the rhs of the last equation
for j in range (i+1, n ) :
if (j!=i): #//then subtract all the lhs values except the coefficient of the variable whose value is being calculated
x[i]=x[i]-a[i][j]*x[j];
x[i]=x[i]/a[i][i]; # //now finally divide the rhs by the coefficient of the variable to be calculated
print( "x",i,"=",round(x[i],4))
print ("\nThe values of the variables are as follows:\n")
for i in range(0 ,n):
print( "x",i,"=",round(x[i],4)) #// Print the values of x, y,z,....
輸出結果
========= RESTART: F:\2018-09勤益科大數值分析\數值分析\PYTHON\EX6-1.py ============
Enter the no. of equations
3
Enter the elements of the augmented-matrix row-wise:
a[ 0 ][ 0 ]= -1.0 a[ 0 ][ 1 ]= 1.0 a[ 0 ][ 2 ]= 2.0 a[ 0 ][ 3 ]= 2.0
a[ 1 ][ 0 ]= 3.0 a[ 1 ][ 1 ]= -1.0 a[ 1 ][ 2 ]= 1.0 a[ 1 ][ 3 ]= 6.0
a[ 2 ][ 0 ]= -1.0 a[ 2 ][ 1 ]= 3.0 a[ 2 ][ 2 ]= 4.0 a[ 2 ][ 3 ]= 4.0
The matrix after Pivotisation is:
3.0 -1.0 1.0 6.0
-1.0 3.0 4.0 4.0
-1.0 1.0 2.0 2.0
The matrix after gauss-elimination is as follows:
3.0 -1.0 1.0 6.0
0.0 2.6667 4.3333 6.0
0.0 0.0 1.25 2.5
x 2 = 2.0
x 1 = -1.0
x 0 = 1.0
The values of the variables are as follows:
x 0 = 1.0
x 1 = -1.0
x 2 = 2.0
>>>
沒有留言:
張貼留言