簡體   English   中英

使用LU分解實現Ax = b求解器時遇到問題

[英]Trouble implementing Ax = b solver using LU decomposition

我試圖解決形式為Ax = b的線性系統,其中A是實數的nxn矩陣和實數的ba1xn向量,使用A = LU算法。

我已經實現了必要的功能,但我不確定問題所在的功能或功能。

import numpy as np

 def forward_sub(L, b):
    """Given a lower triangular matrix L and right-side vector b,
    compute the solution vector y solving Ly = b."""

    y = []
    for i in range(len(b)):
        y.append(b[i])
        for j in range(i):
            y[i]=y[i]-(L[i, j]*y[j])
        y[i] = y[i]/L[i, i]

    return y

def backward_sub(U, y):
    """Given a lower triangular matrix U and right-side vector y,
    compute the solution vector x solving Ux = y."""



    x = [0 for i in range(len(U))]

    for i in range(len(U)-1, 0, -1):
        x[i] = U[i, i]/y[i]
        for j in range (i-1, 0, -1):
            U[i, i] += U[j, i]*x[i]

    return x


def lu_factor(A):


    #LU decompostion using Doolittles method

 L = np.zeros_like(A)
 U = np.zeros_like(A)

 N = np.size(A,0)

 for k in range(N):
        L[k, k] = 1
        U[k, k] = (A[k, k] - np.dot(L[k, :k], U[:k, k])) / L[k, k]
        for j in range(k+1, N):
            U[k, j] = (A[k, j] - np.dot(L[k, :k], U[:k, j])) / L[k, k]
        for i in range(k+1, N):
            L[i, k] = (A[i, k] - np.dot(L[i, :k], U[:k, k])) / U[k, k]


  return (L, U)

def lu_solve(L, U, b):
    # Step 1: Solve Uy = b using forward substitution

    # Step 2: Solve Lx = y using backward substitution

    y = forward_sub(L,b)
    x = backward_sub(U,y)

    return x


def linear_solve(A, b):
    # ...

    L, U = lu_factor(A)
    x = lu_solve(L,U,b)
    return x


b = [6,-4,27]
A = np.matrix([[1,1,1],[0,2,5],[2,5,-1]])

print(linear_solve(A,b))

如上所述選擇A和b得到x = [0,-0.5,-0.42]作為我的解向量,但它應該給出x = [5,3,-2]

A是整數矩陣。 這也使LU整數矩陣,但正確的結果是:

L:
[[1.  0.  0. ]
 [0.  1.  0. ]
 [2.  1.5 1. ]]
U:
[[  1.    1.    1. ]
 [  0.    2.    5. ]
 [  0.    0.  -10.5]]

需要一些小數值。 通常,即使輸入由整數組成,LU分解的情況也是如此。 畢竟有一些分裂正在進行中。

更改數據類型修復了該問題。 例如:

A = np.matrix([[1.,1,1],
               [0,2,5],
               [2,5,-1]])

backward_sub壞了,我不確定究竟是多少,但無論如何它都是一個奇怪的實現。 這個似乎工作:

def backward_sub(U, y):
    """Given a lower triangular matrix U and right-side vector y,
    compute the solution vector x solving Ux = y."""

    x = np.zeros_like(y)

    for i in range(len(x), 0, -1):
      x[i-1] = (y[i-1] - np.dot(U[i-1, i:], x[i:])) / U[i-1, i-1]

    return x

結果是[ 5. 3. -2.] ,嘗試一個ideone

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM