编程语言
首页 > 编程语言> > 用Python实现Gauss-Jordan求逆矩阵

用Python实现Gauss-Jordan求逆矩阵

作者:互联网

Python Gauss-Jordan求逆源码

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)

运行结果:

原矩阵:
 [[11.06620341  4.02653051 -3.81266039 -1.77969821  1.56564016]
 [-4.47705901 13.4555903  -3.43722209  1.87754608 -4.97826586]
 [ 0.82454741 -2.50899308  5.44661861 -1.26801133 -3.07717828]
 [ 3.71653898 -1.33820684 -1.68941373  6.72406738  3.88257595]
 [ 0.56430171  3.53763796 -0.97550277  4.17050773 11.3646953 ]]


变换后的矩阵 A:
 [[ 1.00000000e+00  0.00000000e+00  4.06392813e-17  0.00000000e+00
   0.00000000e+00]
 [ 0.00000000e+00  1.00000000e+00 -2.69147293e-18  0.00000000e+00
   0.00000000e+00]
 [ 0.00000000e+00  0.00000000e+00  1.00000000e+00  0.00000000e+00
   0.00000000e+00]
 [ 0.00000000e+00  0.00000000e+00  9.80494989e-19  1.00000000e+00
   3.05013513e-17]
 [ 0.00000000e+00  0.00000000e+00 -4.75588575e-18  0.00000000e+00
   1.00000000e+00]]


逆矩阵 I:
 [[ 0.07219712 -0.00483262  0.05730815  0.03695309 -0.00917038]
 [ 0.02769365  0.06116294  0.05769089 -0.02894162  0.04848527]
 [-0.00629893  0.02022926  0.20051313 -0.01168842  0.06801452]
 [-0.03631011  0.03778475  0.04093239  0.14723274 -0.01766303]
 [ 0.00057863 -0.03092852 -0.01861346 -0.04785919  0.08567442]]


验证 a 与变换后的 I 互为逆矩阵
[[ 1.00000000e+00  6.75978849e-17  2.04597238e-16  1.22516624e-17
   6.28858572e-17]
 [-3.91192620e-17  1.00000000e+00  2.20470876e-16  1.12105900e-16
   9.66403786e-17]
 [ 1.57751789e-17 -3.58731145e-17  1.00000000e+00 -5.18151179e-17
   5.50296991e-17]
 [ 9.09477972e-18 -4.24848092e-17  1.09681971e-16  1.00000000e+00
   2.58718941e-17]
 [ 6.19235889e-18  5.40502791e-17  1.44604666e-16  1.18687378e-16
   1.00000000e+00]]

标签:求逆,17,Python,矩阵,00,Gauss,0.00000000,1.00000000,print
来源: https://blog.csdn.net/cauchy7203/article/details/114460279