用Python实现Gauss-Jordan求逆矩阵
生活随笔
收集整理的這篇文章主要介紹了
用Python实现Gauss-Jordan求逆矩阵
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Python Gauss-Jordan求逆源碼
import numpy as npn = 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]/divisorI[i][j] = I[i][j]/divisorprint('原矩陣:\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+000.00000000e+00][ 0.00000000e+00 1.00000000e+00 -2.69147293e-18 0.00000000e+000.00000000e+00][ 0.00000000e+00 0.00000000e+00 1.00000000e+00 0.00000000e+000.00000000e+00][ 0.00000000e+00 0.00000000e+00 9.80494989e-19 1.00000000e+003.05013513e-17][ 0.00000000e+00 0.00000000e+00 -4.75588575e-18 0.00000000e+001.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-176.28858572e-17][-3.91192620e-17 1.00000000e+00 2.20470876e-16 1.12105900e-169.66403786e-17][ 1.57751789e-17 -3.58731145e-17 1.00000000e+00 -5.18151179e-175.50296991e-17][ 9.09477972e-18 -4.24848092e-17 1.09681971e-16 1.00000000e+002.58718941e-17][ 6.19235889e-18 5.40502791e-17 1.44604666e-16 1.18687378e-161.00000000e+00]]總結
以上是生活随笔為你收集整理的用Python实现Gauss-Jordan求逆矩阵的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Markdown与 $\LaTeX$ 公
- 下一篇: autograd库测试笔记-(一个基于N