LU分解法求解方程组的代码
时间: 2023-05-29 21:07:09 浏览: 84
LU分解法求解线性方程组
以下是Python代码实现LU分解法求解方程组:
```python
import numpy as np
# LU分解函数
def LU_decomposition(A):
n = len(A)
L = np.eye(n)
U = A.copy()
for j in range(n-1):
for i in range(j+1, n):
L[i][j] = U[i][j] / U[j][j]
U[i][j:] -= L[i][j] * U[j][j:]
return L, U
# 前向替换函数
def forward_substitution(L, b):
n = len(b)
y = np.zeros(n)
for i in range(n):
y[i] = b[i] - np.dot(L[i][:i], y[:i])
return y
# 后向替换函数
def backward_substitution(U, y):
n = len(y)
x = np.zeros(n)
for i in range(n-1, -1, -1):
x[i] = (y[i] - np.dot(U[i][i+1:], x[i+1:])) / U[i][i]
return x
# LU分解法求解方程组
def solve_equation(A, b):
L, U = LU_decomposition(A)
y = forward_substitution(L, b)
x = backward_substitution(U, y)
return x
# 测试
A = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
b = np.array([1, 2, 3])
x = solve_equation(A, b)
print(x)
```
输出结果为:
```
[-0.66666667 1.33333333 -0.66666667]
```
表示方程组的解为 $x_1=-\frac{2}{3}$,$x_2=\frac{4}{3}$,$x_3=-\frac{2}{3}$。
阅读全文