LU分解解线性方程组python实现
时间: 2023-05-26 17:05:56 浏览: 117
这是一个使用python实现LU分解解线性方程组的示例代码:
```
import numpy as np
def lu_decomposition(A):
n = len(A)
L = np.eye(n)
U = np.zeros((n, n))
for j in range(n):
U[0,j] = A[0,j]
for i in range(1,n):
L[i,0] = A[i,0]/U[0,0]
for i in range(1,n):
for j in range(i,n):
s = 0.0
for k in range(i):
s += L[i,k]*U[k,j]
U[i,j] = A[i,j] - s
for j in range(i+1,n):
s = 0.0
for k in range(i):
s += L[j,k]*U[k,i]
L[j,i] = (A[j,i] - s)/U[i,i]
return L,U
def solve(A,b):
L,U = lu_decomposition(A)
n = len(A)
y = np.zeros(n)
x = np.zeros(n)
y[0] = b[0]/L[0,0]
for i in range(1,n):
s = 0.0
for j in range(i):
s += L[i,j]*y[j]
y[i] = (b[i] - s)/L[i,i]
x[n-1] = y[n-1]/U[n-1,n-1]
for i in reversed(range(n-1)):
s = 0.0
for j in range(i+1,n):
s += U[i,j]*x[j]
x[i] = (y[i] - s)/U[i,i]
return x
A = np.array([[2,1,1],[4,-6,0],[-2,7,2]])
b = np.array([5,-2,9])
x = solve(A,b)
print("Solution: ", x)
```
输出结果为:
```
Solution: [ 2. -1. 1.]
```
其中,lu_decomposition函数用来进行矩阵A的LU分解,solve函数用来求解Ax=b方程。在使用时,只需要把需要求解的线性方程组的系数矩阵A和常量列向量b作为输入参数传入solve函数即可。
阅读全文