矩阵的QR分解,基于施密特算法的python实现

今天有师妹来叫我帮忙写个矩阵的QR分解,emmm写完代码顺便写个博客记录一下。。。
教材来源:应用数值代数(译本)
矩阵的QR分解,基于施密特算法的python实现_第1张图片
矩阵的QR分解,基于施密特算法的python实现_第2张图片

import numpy as np

def CGS(A):
    w, _ = A.shape
    Q = np.zeros_like(A, dtype=np.float32)
    R = np.copy(Q)
    for i in range(w):
        a = A.T[i]
        q = np.copy(a)
        for j in range(0, i):
            r = np.dot(Q[:,j],a) 
            R[j,i] = r
            q -= np.dot(r,Q[:,j])
        q_norm = np.linalg.norm(q)
        R[i,i] = q_norm
        Q[:,i] = q/q_norm
    return Q, R  

def Input_A():
    length = int(input('请输入矩阵的大小:'))
    A = list()
    for i in range(length):
        r = '请输入矩阵第%d行(用空格隔开):'%(i+1)
        a = list(map(float,input(r).split()))
        A.append(a)
    return np.array(A, dtype=np.float32)

def main():
    A = Input_A()
    Q, R = CGS(A)
    print('Q = \n', Q)
    print('R = \n', R)
    print('QR = \n', np.dot(Q, R))
    
if __name__ == '__main__':
    main()

你可能感兴趣的:(数学)