我正在嘗試在不使用 Numpy 的 3x3 矩陣(不使用任何庫函式)的情況下計算 Matrix 的冪 'n'
這是我到目前為止撰寫的代碼:
def matmul(M1, M2):
a1 = (M1[0][0]*M2[0][0]) (M1[0][1] * M2[1][0]) (M1[0][2] * M2[2][0])
a2 = (M1[0][0]*M2[0][1]) (M1[0][1] * M2[1][1]) (M1[0][2] * M2[2][1])
a3 = (M1[0][0]*M2[0][2]) (M1[0][1] * M2[1][2]) (M1[0][2] * M2[2][2])
a4 = (M1[1][0]*M2[0][0]) (M1[1][1] * M2[1][0]) (M1[1][2] * M2[2][0])
a5 = (M1[1][0]*M2[0][1]) (M1[1][1] * M2[1][1]) (M1[1][2] * M2[2][1])
a6 = (M1[1][0]*M2[0][2]) (M1[1][1] * M2[1][2]) (M1[1][2] * M2[2][2])
a7 = (M1[2][0]*M2[0][0]) (M1[2][1] * M2[1][0]) (M1[2][2] * M2[2][0])
a8 = (M1[2][0]*M2[0][1]) (M1[2][1] * M2[1][1]) (M1[2][2] * M2[2][1])
a9 = (M1[2][0]*M2[0][2]) (M1[2][1] * M2[1][2]) (M1[2][2] * M2[2][2])
return [[a1, a2, a3], [a4, a5, a6], [a7, a8, a9]]
def matpow(mat, p):
if p == 1:
return mat
m2 = matpow(mat, p//2)
if p%2 == 0:
return matmul(m2, m2)
else:
return matmul(matmul(m2, m2), mat)
這適用于較小數量的“n”,但在應用于大數字時會失敗并出現以下錯誤:
File "/workspace/default/solution.py", line 17, in matpow
m2 = matpow(mat, p//2)
File "/workspace/default/solution.py", line 17, in matpow
m2 = matpow(mat, p//2)
[Previous line repeated 990 more times]
File "/workspace/default/solution.py", line 15, in matpow
if p == 1:
RecursionError: maximum recursion depth exceeded in comparison
似乎在嘗試大量時達到了遞回堆疊深度,有沒有一種方法可以在不使用庫的情況下以優化的方式實作功能?
uj5u.com熱心網友回復:
如果 power 引數真的很大,則使用迭代解決方案,通過迭代 power 的二進制位:
def matpow(mat, p):
# Start with the identity matrix. This way it will also work for p==0
# If you are using floats, then make this also with floats:
result = [[1,0,0],[0,1,0],[0,0,1]]
while p > 0:
if p & 1:
result = matmul(result, mat)
mat = matmul(mat, mat)
p >>= 1
return result
uj5u.com熱心網友回復:
使用遞回時,堆會在記憶體中新建一條記錄來存放回傳暫存器,這樣每次呼叫函式時matpow,程式就知道在滿足條件時要回傳哪個暫存器。因此,我不使用遞回,而是使用迭代。
使用 while/for 回圈來迭代,直到找到正確的值。
這應該作業(測驗),
def matpow_iteratively(mat, p):
new_mat = mat
arr = []
while p > 1:
arr.append(p)
p = p // 2
index = len(arr) - 1
while index >= 0:
if arr[index] % 2 == 0:
new_mat = matmul(new_mat, new_mat)
else:
new_mat = matmul(matmul(new_mat, new_mat), mat)
index = index - 1
return new_mat
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/408847.html
標籤:
