設計了一個測試函數,傳入原矩陣和其最大秩分解,列向量。函數依次輸出以下內容
- 1、判斷當前給出的最大秩分解是否正確
- 2、給出的M-P廣義逆
- 3、判斷矩陣是否相容
- 4、若矩陣相容則輸出的最小范數解和通解
- 5、若不相容則輸出的最小二乘解、通解和最佳逼近解
運行環境: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()
給出的測試用例test1來自於2014年第8題。輸出結果爲
第二個題爲書上P233 21題第一小題,運行結果爲: