我正在尝试使用 python 实现一个原始的(不导入库,如 scipy 或 numpy)用于方阵的 Doolittle LU 分解。到目前为止,这是我的代码。
def luDecomposition(mat, n):
lower = [[0 for x in range(n)]
for y in range(n)]
upper = [[0 for x in range(n)]
for y in range(n)]
# Decomposing matrix into Upper
# and Lower triangular matrix
for i in range(n):
# Upper Triangular
for k in range(i, n):
# Summation of L(i, j) * U(j, k)
soma = 0
for j in range(i):
soma += (lower[i][j] * upper[j][k])
# Evaluating U(i, k)
upper[i][k] = mat[i][k] - soma
# Lower Triangular
for k in range(i, n):
if (i == k):
lower[i][i] = 1 # Diagonal as 1
else:
# Summation of L(k, j) * U(j, i)
soma = 0
for j in range(i):
soma += (lower[k][j] * upper[j][i])
# Evaluating L(k, i)
lower[k][i] = int((mat[k][i] - soma) /
upper[i][i])
# setw is for displaying nicely
print(" L \t\t U ")
# Displaying the result :
for i in range(n):
# Lower
for j in range(n):
print(lower[i][j], end="\t")
print("", end="\t")
# Upper
for j in range(n):
print(upper[i][j], end="\t")
print("")
# Driver code
mat = [[4, 2, -1, 1],
[8, 4, 2, -2],
[1, 4, 2, -2],
[2, 1, -2, 6]]
luDecomposition(mat, 4)
但是,我收到以下错误:
lower[k][i] = int((mat[k][i] - soma) / ZeroDivisionError : 除以零。
直到现在我都无法解决这个问题。我的代码有任何理论上的错误吗?