使用 Thomas 算法的三对角矩阵的逆

问题描述 投票:0回答:0

我有一个三对角矩阵,想用 Thomas 算法求逆。下面是我的代码 当我运行它时,我得到了一个三对角线的逆。当我使用“np.linalg.inv”函数时与相同的矩阵进行比较,得到完全不同的结果。倒数不是唯一的吗?我的代码有问题吗?

import numpy as np
# Define the shape of the tridiagonal matrix
n = 5

# Generate the tridiagonal matrix with main diagonal values of 2 and upper/lower diagonals with values of 1
diag = np.ones(n) * 2
upper_diag = np.ones(n-1)
lower_diag = np.ones(n-1)

# Construct the tridiagonal matrix A
A = np.diag(diag) + np.diag(upper_diag, k=1) + np.diag(lower_diag, k=-1)

# Initialize the In-Place LU factorization using Thomas algorithm
for j in range(1, n-1):
    diag[j] -= lower_diag[j-1] * (upper_diag[j-1]/diag[j-1])
    upper_diag[j] /= diag[j]
    print("After step", j, ":\n", np.diag(diag) + np.diag(upper_diag, k=1))

# Compute the inverse of the matrix using the In-Place LU factorization
inv_A = np.zeros_like(A)
inv_A[-1,-1] = 1/ diag[-1]

for j in range(n-2, -1, -1):
    inv_A[j,j] = 1/diag[j]
    inv_A[j,j+1] = -upper_diag[j]
    inv_A[j+1,j] = -lower_diag[j]
    inv_A[j,j+1] /= diag[j+1]
    inv_A[j+1,j+1] += upper_diag[j] * inv_A[j,j+1]

# Print the tridiagonal matrix and its inverse
print("Tridiagonal Matrix A:\n", A)
print("Inverse of A:\n", inv_A)
sparse-matrix matrix-inverse
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.