Python实现Crout矩阵分解

时间:2017-10-08 10:38:46

标签: python numpy

我正在尝试编写Crout矩阵分解的Python实现,它适用于3x3矩阵。我只允许使用numpy包。这是我到目前为止的尝试:

import numpy as np

def crout(A: np.ndarray):

    L = np.zeros((3, 3))
    U = np.zeros((3, 3))

    for k in range(0, 3):
        U[k, k] = 1

        for j in range(k, 3):
            sum0 = sum(L[k, s] * U[s, j] for s in range(1, k-1))
            L[k, j] = A[k, j] - sum0

        for j in range(k, 3):
            sum1 = sum(L[k, s] * U[s, j] for s in range(1, k-1))
            U[k, j] = (A[k, j] - sum1) / L[k, k]

    print(" L =", '\n', L, '\n', " U =", '\n', U)
    return L, U

A = np.array([[60.0, 30.0, 20.0], [30.0, 20.0, 15.0], [20.0, 15.0, 12.0]])
crout(A)

我尝试在矩阵A上使用我的函数,它应该产生:

enter image description here

但是给出了

enter image description here

所以,显然输出是错误的。我的索引是错误还是还有其他问题?

2 个答案:

答案 0 :(得分:0)

看起来你在第二个for循环中翻转了j和#k

def crout(A):

    L = np.zeros((3, 3))
    U = np.zeros((3, 3))

    for k in range(0, 3):
        U[k, k] = 1

        for j in range(k, 3):
            sum0 = sum(L[k, s] * U[s, j] for s in range(1, k-1))
            #reversed
            L[j, k] = A[k, k] - sum0

        for j in range(k, 3):
            sum1 = sum(L[k, s] * U[s, j] for s in range(1, k-1))
            U[k, j] = (A[k, j] - sum1) / L[k, k]

    print L
    print U
    return L, U

答案 1 :(得分:0)

不仅指数反转了,而且范围也作了一些调整。下面的代码返回期望的矩阵。

import numpy as np

def crout(A):

    L = np.zeros((3, 3))
    U = np.zeros((3, 3))

    for k in range(0, 3):
        U[k, k] = 1 

        for j in range(i, 3):
            sum0 = sum([L[j, s] * U[s, k] for s in range(0, j)]) #range from index 0
            L[j, k] = A[j, k] - sum0 #reversed index

        for j in range(k+1, 3):
            sum1 = sum([L[k, s] * U[s, j] for s in range(0, i)]) #range from index 0
            U[k, j] = (A[k, j] - sum1) / L[k, k]



    print(L)
    print()
    print(U)
    return L, U

A = np.array([[60.0, 30.0, 20.0], [30.0, 20.0, 15.0], [20.0, 15.0, 12.0]])
crout(A)