2019-07-01 08:10:18 +00:00
|
|
|
|
"""Lower-Upper (LU) Decomposition."""
|
|
|
|
|
|
2018-11-05 17:19:08 +00:00
|
|
|
|
# lower–upper (LU) decomposition - https://en.wikipedia.org/wiki/LU_decomposition
|
2018-10-19 12:48:28 +00:00
|
|
|
|
import numpy
|
|
|
|
|
|
2019-07-01 08:10:18 +00:00
|
|
|
|
|
|
|
|
|
def LUDecompose(table):
|
2018-11-05 17:19:08 +00:00
|
|
|
|
# Table that contains our data
|
|
|
|
|
# Table has to be a square array so we need to check first
|
2019-07-01 08:10:18 +00:00
|
|
|
|
rows, columns = numpy.shape(table)
|
|
|
|
|
L = numpy.zeros((rows, columns))
|
|
|
|
|
U = numpy.zeros((rows, columns))
|
|
|
|
|
if rows != columns:
|
2018-11-05 17:19:08 +00:00
|
|
|
|
return []
|
2019-07-01 08:10:18 +00:00
|
|
|
|
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
|
|
|
|
|
|
2018-10-19 12:48:28 +00:00
|
|
|
|
|
2018-11-05 17:19:08 +00:00
|
|
|
|
if __name__ == "__main__":
|
2019-07-01 08:10:18 +00:00
|
|
|
|
matrix = numpy.array([[2, -2, 1],
|
|
|
|
|
[0, 1, 2],
|
|
|
|
|
[5, 3, 1]])
|
|
|
|
|
L, U = LUDecompose(matrix)
|
2018-11-05 17:19:08 +00:00
|
|
|
|
print(L)
|
|
|
|
|
print(U)
|