快速驗證矩陣求MP廣義逆及最小范數解或最小二乘解是否正確

\quad設計了一個測試函數,傳入原矩陣AA和其最大秩分解B,D,A=BDB,D,A=BD,列向量bb。函數依次輸出以下內容

  • 1、判斷當前給出的最大秩分解是否正確
  • 2、給出AA的M-P廣義逆A+A^+
  • 3、判斷矩陣是否相容
  • 4、若矩陣相容則輸出Ax=bAx=b的最小范數解和通解
  • 5、若不相容則輸出Ax=bAx=b的最小二乘解、通解和最佳逼近解

\quad運行環境:Python3+numpy庫

import numpy as np

def same(A, B):
	m = len(A)
	n = len(A[0])
	A = A.tolist()
	B = B.tolist()
	for i in range(m):
		for j in range(n):
			if(abs(A[i][j]-B[i][j])>0.0001):
				return False;
	return True
def run(A, B, D, b):
	"""A爲原矩陣,A=BD爲其最大秩分解,Ax=b"""
	A = np.mat(A)
	B = np.mat(B)
	D = np.mat(D)
	b = np.mat(b).reshape(len(b), 1)
	if(same(B*D, A)):
		print("最大秩分解正確")
	else:
		print("最大秩分解錯誤")
	Ap = D.T * np.linalg.inv(D*D.T) * np.linalg.inv(B.T*B) * B.T
	print("M-P廣義逆爲:\n", Ap)
	if(same(A*Ap*b, b)):
		print("該方程相容")
		x = Ap*b
		print("最小范數解爲:\n", x)
		E = np.eye(len(x))
		print("通解爲:\n{}+{}U".format(x, E-Ap*A))
	else:
		print("該方程不相容")
		x = Ap*b
		print("最小二乘解爲:\n", x)
		E = np.eye(len(x))
		print("最小二乘解通解爲:\n{}+{}U".format(x, E-Ap*A))
		print("最佳逼近解爲:\n", x)

def test1():
	A = [[0, 1, -1],
	     [-1, 0, 1],
	     [1, -1, 0],
	     [0, 1, -1]]
	B = [[0, 1], [-1, 0], [1, -1], [0, 1]]
	D = [[1, 0, -1], [0, 1, -1]]
	b = [1, -1, 0, 1]
	run(A, B, D, b)

def test2():
	A = [[0, 0, 2], [1, 1, 0], [0, 0, 1], [1, 1, 1]]
	B = [[0, 2], [1, 0], [0, 1], [1, 1]]
	D = [[1, 1, 0], [0, 0, 1]]
	b = [1, 1, 1, 1]
	run(A, B, D, b)

if __name__ == '__main__':
    test1()
    test2()

\quad給出的測試用例test1來自於2014年第8題。輸出結果爲
在這裏插入圖片描述
\quad第二個題爲書上P233 21題第一小題,運行結果爲:
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章