LU分解python实现

import numpy as np
def LU(A):
  '''
  生成值全位0的U矩阵,和单位矩阵L
  '''
   L = np.eye(len(A)) 
   U = np.zeros(np.shape(A))
   for r in range(1,len(A)): #求U的第一行和L的第一列
      U[0,r-1] = A[0,r-1]
      L[r,0] = A[r,0]/A[0,0]
   U[0,-1] = A[0,-1]
   for r in range(1,len(A)):#先求U再求L     
      for i in range(r,len(A)):
         delta = 0                   
         for k in range(0,r):   #求∑(???∗???)
            delta += L[r,k]*U[k,i] 
         U[r,i] = A[r,i] - delta 
                  
         for i in range(r+1,len(A)):#求L矩阵
            theta = 0 
            for k in range(0,r):  #求∑(?i?∗??r)
               theta += L[i,k]*U[k,r]
            L[i,r] = (A[i,r] - theta)/U[r,r]
   return L,U
   
A= np.array([[1,1,-1], [1,2,-2.],[-2,1,1]])
L,U = LU(A)
print(L,U)

让我们验证一下结果
LU分解python实现_第1张图片

你可能感兴趣的:(LU分解python实现)