例題6-8 利用LU分解求行列式的值
# Python Program to Perform LU Decomposition of any Matrix
def lu(a,l,u,n):
for i in range(0 , n):
for j in range(0 , n):
if (j < i):
l[j][i] = 0;
else:
l[j][i] = a[j][i];
for k in range (0 , i):
l[j][i] = l[j][i] - l[j][k] * u[k][i];
for j in range(0 , n):
if (j < i):
u[i][j] = 0;
elif (j == i):
u[i][j] = 1
else:
u[i][j] = a[i][j] / l[i][i];
for k in range (0 , i):
u[i][j] = u[i][j] - ((l[i][k] * u[k][j]) / l[i][i]);
#+++++++++++++++++++++++++++++++++++++++++
n=3
print("\nEnter size of 2d array(Square matrix) : ",n)
a= [ [0.0 for i in range(n+1)] for j in range(n+1) ] #[n][n+1],
l= [ [0.0 for i in range(n+1)] for j in range(n+1) ] #[n][n+1],
u= [ [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)];
print("\nEnter the elements of the augmented-matrix row-wise:\n")
'''
a=[[2.0 , 1.0 , -3.0 , 0.0],
[-1.0 , 3.0 , 2.0, 0.0],
[3.0 , 1.0 , -3.0 , 0.0]]
'''
a=[[4.0 , -2.0 , 1.0 ],
[3.0 , 0.0 , -5.0],
[1.0 , -3.0 , -4.0]]
for i in range(0 ,n):
for j in range(0,n):
print( "a[",i,"][",j,"]=",round(a[i][j],4),'\t',end='')
print("")
lu(a, l, u, n);
print("\nL Decomposition\n\n")
for i in range(0 ,n):
for j in range(0,n):
print( "L[",i,"][",j,"]=",round(l[i][j],4),'\t',end='')
print("")
print("\nU Decomposition\n\n")
for i in range(0 ,n):
for j in range(0,n):
print( "U[",i,"][",j,"]=",round(u[i][j],4),'\t',end='')
print("")
det=1.0
for i in range(0 ,n):
det=det *l[i][i]
print( "\ndet A=",round(det,4) )
輸出畫面
============= RESTART: F:/2018-09勤益科大數值分析/數值分析/PYTHON/EX6-7-1.py =============
Enter size of 2d array(Square matrix) : 3
Enter the elements of the augmented-matrix row-wise:
a[ 0 ][ 0 ]= 2.0 a[ 0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