L和U的逆矩阵计算不要用np.linalg.inv
时间: 2024-02-24 22:58:36 浏览: 101
好的,我们可以通过手动计算L和U的逆矩阵来实现。下面是修改后的代码:
```python
import numpy as np
A = np.array([[1, 3, 5], [2, 4, 7], [1, 1, 0]])
b = np.array([[1], [2], [3]])
# 进行LU分解
n = A.shape[0]
L = np.eye(n) # 初始化L为单位矩阵
U = np.zeros_like(A) # 初始化U为零矩阵
for j in range(n):
# 计算U的第j行
U[j][j:] = A[j][j:] - np.dot(L[j][0:j], U[0:j][j:])
# 计算L的第j列
if j < n - 1:
L[(j+1):, j] = (A[(j+1):, j] - np.dot(L[(j+1):, 0:j], U[0:j, j])) / U[j][j]
# 进行前代法求解Ly=b
y = np.zeros_like(b)
for i in range(len(b)):
y[i] = b[i]
for j in range(i):
y[i] -= L[i][j] * y[j]
# 进行回代法求解Ux=y
x = np.zeros_like(b)
for i in range(len(b)-1, -1, -1):
x[i] = y[i]
for j in range(i+1, len(b)):
x[i] -= U[i][j] * x[j]
x[i] /= U[i][i]
# 计算L的逆矩阵
L_inv = np.zeros_like(L)
for i in range(n):
L_inv[i][i] = 1 / L[i][i]
for j in range(i+1, n):
L_inv[j][i] = -np.dot(L[j][i:j], L_inv[i:j, i]) / L[j][j]
# 计算U的逆矩阵
U_inv = np.zeros_like(U)
for i in range(n-1, -1, -1):
U_inv[i][i] = 1 / U[i][i]
for j in range(i):
U_inv[j][i] = -np.dot(U[j][i+1:], U_inv[i+1:, i]) / U[j][j]
# 计算A的逆矩阵
A_inv = np.dot(U_inv, L_inv)
print(A_inv)
```
该代码实现了手动计算A矩阵的LU分解,并通过前代法和回代法求解线性方程组Ax=b,然后通过手动计算L和U的逆矩阵来计算A的逆矩阵。
阅读全文