LU分解 python
时间: 2023-11-07 14:04:17 浏览: 81
LU分解是一种矩阵分解的方法,用于求解线性方程组Ax=b。在LU分解中,矩阵A被分解为一个下三角矩阵L和一个上三角矩阵U,即A=LU。其中,L的对角线元素为1,U的对角线元素为L中每一行对应位置的系数。
以下是一个用Python实现LU分解的完整代码,并输出了L、U矩阵和解x的结果:
```python
import numpy as np
from scipy import linalg
def LU_decomposition(A, b):
n = len(A[0])
L = np.zeros([n, n])
U = np.zeros([n, n])
for i in range(n):
L[i][i] = 1
if i == 0:
U[0][0] = A[0][0]
for j in range(1, n):
U[0][j] = A[0][j]
L[j][0] = A[j][0] / U[0][0]
else:
for j in range(i, n):
temp = 0
for k in range(0, i):
temp += L[i][k] * U[k][j]
U[i][j] = A[i][j] - temp
for j in range(i + 1, n):
temp = 0
for k in range(0, i ):
temp += L[j][k] * U[k][i]
L[j][i] = (A[j][i] - temp) / U[i][i]
Z = linalg.solve(L, b)
x = linalg.solve(U, Z)
print("L =", L)
print("U =", U)
print("Z =", Z)
print("Exact solution: x =", x)
# 定义A、b的值
A = [[-3, -5, 10, 13], [2, 0, -4, 6], [8, -2, 1, -3], [5, -1, 1, 15]]
b = [-14, 8, 7, 0]
LU_decomposition(A, b)
```
阅读全文