我需要解決整個範圍的8x8和9x9矩陣,所以我認爲我可以建立一個Python程序,使整個事情更容易。解決與gausian emlinination與蟒蛇樞軸的9x9矩陣
到目前爲止我已成功地創建:
from __future__ import division
import numpy as np
def solveEqns(A,v):
def lu(A):
#Factor A into LU by Gaussian elimination with scaled partial pivoting
n, m = np.shape(A)
if n != m:
print "Error: input matrix is not square"
return None
# Generate initial index vector
p = range(n)
# Determine the largest (in magnitude) element in each row. These
# factors are used to scale the pivot elements for comparison purposes
# when deciding which row to use as a pivot row.
s = [0] * n
for i in xrange(n):
smax = 0.0
for j in xrange(n):
smax = max(smax, abs(A[i][j]))
s[i] = smax
# Begin Gaussian elimination.
for k in xrange(n - 1):
# Find the remaining row with the largest scaled pivot.
rmax = 0.0
for i in xrange(k, n):
r = abs(A[p[i][k]]/s[p[i]])
if r > rmax:
rmax = r
j = i
# Row j has the largest scaled pivot, so "swap" that row with the
# current row (row k). The swap is not actually done by copying rows,
# but by swaping two entries in an index vector.
p[j], p[k] = (p[k], p[j])
# Now carry out the next elimination step as usual, except for the
# added complication of the index vector.
for i in xrange(k + 1, n):
xmult = A[p[i],k]/A[p[k],k]
A[p[i],k] = xmult
for j in xrange(k + 1, n):
A[p[i],j] = A[p[i],j] - xmult * A[p[k],j]
# All done, return factored matrix A and permutation vector p
return (A, p)
def solve(A, p, b):
#Solves Ax = b given an LU factored matrix A and permuation vector p
n, m = np.shape(A)
if n != m:
print "Error: input matrix is not square"
return None
# Forward solve
x = np.zeros(n)
for k in xrange(n - 1):
for i in xrange(k + 1, n):
b[p[i]] = b[p[i]] - A[p[i],k] * b[p[k]]
# Backward solve
for i in xrange(n - 1, -1, -1):
sum = b[p[i]]
for j in xrange(i + 1, n):
sum = sum - A[p[i],j] * x[j]
x[i] = sum/A[p[i],i]
# All done, return solution vector
return x
lu(A)
return solve(A,p,v)
DEF電路():
A = np.array([[1,0,0,0,0,8,0,0,0],[0,1,0,0,5,0,0,0,0],[0,1,0,0,5,0,0,0,0],[0,0,0,1,-1,1,0,0,0],[0,0,1,0,0,0,1,-1,0],[0,0,1,0,0,0,1,0,-1],[0,1,0,0,-1,0,0,0,1],[1,0,0,0,0,-1,0,1,0],[1,-1,0,1,0,0,0,0,0]])
v = np.array([9,-12,-0.5,0,0,0,0,0,0])
I = solveEqns(A,v)
return I
解決9x9的矩陣A在末端。這是我需要解決的更容易的一個,所以可以在python之外解決它,以檢查結果是否準確。
即時得到上線26回溯錯誤:
回溯(最近通話最後一個):
File "<ipython-input-110-6daf773db1e3>", line 1, in <module>
solveEqns(A,b)
File "C:/Users/SamMc/Documents/Python Scripts/q6u1510416 v4.py", line 65, in solveEqns
lu(A)
File "C:/Users/SamMc/Documents/Python Scripts/q6u1510416 v4.py", line 26, in lu
r = abs(A[p[i][k]]/s[p[i]])
TypeError: 'int' object has no attribute '__getitem__'
我無法弄清楚爲什麼它不通過從矩陣的一些拉動。
任何幫助將不勝感激。
感謝
山姆
'p [i] [k]' - 再讀一遍。另外,爲什麼不使用執行此任務的NumPy內置插件? – user2357112
因爲numpy不是在這裏發明的! –
使用numpy,然後繼續前進,編寫自己的函數用於使用慢,Python循環進行高斯消元,當numpy的全部點是它是一個科學計算包,並綁定到低級矩陣代數例程 –