LU分解 python实现

以下是使用python实现LU分解,代码写的很丑,不要喷。。。

 

# -*- coding: utf-8 -*-
"""
Created on Sun Dec  3 10:03:45 2017

@author: www
"""

#   python实现LU分解

import numpy as np


def my_LU(B):
    A = np.array(B)
    n = len(A)
    #print(A)
    
    L = np.zeros(shape=(n,n))
    U = np.zeros(shape=(n,n))
    

    for k in range(n-1):
        gauss_vector = A[:,k]
        gauss_vector[k+1:] = gauss_vector[k+1:] / gauss_vector[k]
        gauss_vector[0:k+1] = np.zeros(k+1)
        #print(gauss_vector) 
        L[:,k] = gauss_vector
        L[k][k] = 1.0
        #print(L)
        #print(A)
        for l in range(k+1,n):
            B[l,:] = B[l,:] - gauss_vector[l] * B[k,:]
        
        A = np.array(B)
    L[k+1][k+1] = 1.0
    U = A
    print(U)
    print(L)
    
def main():
    A = np.array([[2., 2., 3.],
                  [4., 7., 7.],
                  [-2.,4., 5.]])
    my_LU(A)
        
     
main()     
     
     

 

 

 

 

 

 

你可能感兴趣的:(python语法,数值分析)