我有一個A*x = B
形式的方程組,其中[A]
是一個三對角線係數矩陣。使用Numpy求解器numpy.linalg.solve
我可以求解x的方程組。優化三對角線係數矩陣的A * x = B解
請參閱下面的示例以瞭解如何開發三角形[A]
martix。該{B}
載體,解決了x
:
# Solve system of equations with a tridiagonal coefficient matrix
# uses numpy.linalg.solve
# use Python 3 print function
from __future__ import print_function
from __future__ import division
# modules
import numpy as np
import time
ti = time.clock()
#---- Build [A] array and {B} column vector
m = 1000 # size of array, make this 8000 to see time benefits
A = np.zeros((m, m)) # pre-allocate [A] array
B = np.zeros((m, 1)) # pre-allocate {B} column vector
A[0, 0] = 1
A[0, 1] = 2
B[0, 0] = 1
for i in range(1, m-1):
A[i, i-1] = 7 # node-1
A[i, i] = 8 # node
A[i, i+1] = 9 # node+1
B[i, 0] = 2
A[m-1, m-2] = 3
A[m-1, m-1] = 4
B[m-1, 0] = 3
print('A \n', A)
print('B \n', B)
#---- Solve using numpy.linalg.solve
x = np.linalg.solve(A, B) # solve A*x = B for x
print('x \n', x)
#---- Elapsed time for each approach
print('NUMPY time', time.clock()-ti, 'seconds')
所以我的問題涉及到上面的例子中的兩個部分:
- 因爲我處理了
[A]
一個角矩陣,也稱爲帶狀矩陣,有沒有更有效的方法來解決方程組而不是使用numpy.linalg.solve
? - 此外,有沒有更好的方法來創建三角對角矩陣,而不是使用
for-loop
?
上述示例根據time.clock()
函數在Linux上運行約0.08 seconds
。
的numpy.linalg.solve
功能工作正常,但我試圖找到一種方法,在進一步加快解決方案的希望採取的[A]
的三對角形式的優勢,然後將該方法更加複雜的例子。
你的意思是像scipy.linalg.solve_banded()? –
@CraigJCopi'scipy.linalg.solve_banded()'需要LU元組。計算LU元組然後求解solve_banded會更快嗎? – wigging
您可以在這裏使用Thomas算法,這可能會更快。維基百科有一個實現http://en.wikipedia.org/wiki/Tridiagonal_matrix_algorithm#Python – y300