lu三角分解法解方程组python代码
时间: 2023-10-13 19:29:10 浏览: 111
以下是使用LU分解法求解线性方程组的Python代码:
```python
import numpy as np
def LU_decomposition(A):
n = A.shape[0]
L = np.eye(n)
U = A.copy()
for k in range(n-1):
for i in range(k+1, n):
if U[i,k] != 0.0:
lam = U[i,k]/U[k,k]
U[i,k+1:n] = U[i,k+1:n] - lam*U[k,k+1:n]
L[i,k] = lam
return L, U
def solve(A, b):
L, U = LU_decomposition(A)
y = np.zeros_like(b)
n = A.shape[0]
# Solve Ly = b
for i in range(n):
y[i] = b[i]
for j in range(i):
y[i] -= L[i,j]*y[j]
y[i] /= L[i,i]
# Solve Ux = y
x = np.zeros_like(b)
for i in range(n-1, -1, -1):
x[i] = y[i]
for j in range(i+1, n):
x[i] -= U[i,j]*x[j]
x[i] /= U[i,i]
return x
```
其中,`LU_decomposition`函数用于计算矩阵A的LU分解,返回L和U矩阵。`solve`函数用于求解线性方程组Ax=b,先利用L矩阵求解Ly=b,再利用U矩阵求解Ux=y。最终返回x向量作为方程组的解。
阅读全文