forked from TheAlgorithms/Python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlu_decomposition.py
32 lines (30 loc) · 944 Bytes
/
lu_decomposition.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# lower–upper (LU) decomposition - https://en.wikipedia.org/wiki/LU_decomposition
import numpy
def LUDecompose (table):
# Table that contains our data
# Table has to be a square array so we need to check first
rows,columns=numpy.shape(table)
L=numpy.zeros((rows,columns))
U=numpy.zeros((rows,columns))
if rows!=columns:
return []
for i in range (columns):
for j in range(i-1):
sum=0
for k in range (j-1):
sum+=L[i][k]*U[k][j]
L[i][j]=(table[i][j]-sum)/U[j][j]
L[i][i]=1
for j in range(i-1,columns):
sum1=0
for k in range(i-1):
sum1+=L[i][k]*U[k][j]
U[i][j]=table[i][j]-sum1
return L,U
if __name__ == "__main__":
matrix =numpy.array([[2,-2,1],
[0,1,2],
[5,3,1]])
L,U = LUDecompose(matrix)
print(L)
print(U)