import numpy as np
n = 5
a = np.random.rand(n,n)*10-5 + np.eye(n)*10
I = np.eye(n)
A = a.copy()
for i in range(n):
if A[i][i] == 0.0:
sys.exit('Divide by zero detected!')
for j in range(n):
if i != j:
ratio = A[j][i]/A[i][i]
for k in range(n):
A[j][k] = A[j][k] - ratio * A[i][k]
I[j][k] = I[j][k] - ratio * I[i][k]
for i in range(n):
divisor = A[i][i]
for j in range(n):
A[i][j] = A[i][j]/divisor
I[i][j] = I[i][j]/divisor
print('原矩阵:\r\n',a)
print('\r\n')
print('变换后的矩阵 A:\r\n',A)
print('\r\n')
print('逆矩阵 I:\r\n',I)
print('\r\n')
print('验证 a 与变换后的 I 互为逆矩阵')
print(a @ I)