编程语言
首页 > 编程语言> > 【PLA】基于Python实现的线性代数算法库之lu分解

【PLA】基于Python实现的线性代数算法库之lu分解

作者:互联网

【PLA】基于Python实现的线性代数算法库之lu分解

算法包下载链接:https://download.csdn.net/download/qq_42629529/79481514

from .Matrix import Matrix
from .Vector import Vector
from ._globals import is_zero#判断是否为0

#方阵的lu分解
def lu(matrix):

    assert matrix.row_num() == matrix.col_num(), "matrix must be a square matrix"

    n = matrix.row_num()#行数
    A = [matrix.row_vector(i) for i in range(n)]#矩阵的行向量,上三角矩阵

    L = [[1.0 if i == j else 0.0 for i in range(n)] for j in range(n)]
    #高斯消元的过程
    for i in range(n):
        # 看A[i][i]位置是否可以是主元
        if is_zero(A[i][i]):
            return None, None#不能分解两个都空
        else:
            for j in range(i + 1, n):
                p = A[j][i] / A[i][i]
                A[j] = A[j] - p * A[i]
                L[j][i] = p
                
    return Matrix(L), Matrix([A[i].underlying_list() for i in range(n)])

标签:matrix,Python,range,lu,PLA,import,row,Matrix
来源: https://blog.csdn.net/qq_42629529/article/details/122800516