繁体   English   中英

没有numpy的矩阵求幂

[英]Matrix exponentiation without numpy

我需要编写一个函数来执行矩阵的常用幂运算

def matrix_power(a, power):
    rows, columns = len(a), len(a[0])
    result = np.zeros((rows, columns))
    b = a
    for step in range(1, power):
        for i in range(0, rows):
            for j in range(0, columns):
                for m in range(0, rows):
                    result[i][j] += a[i][m] * b[m][j]
        a = result
    return result
matrix_power(matrix, 3)

但出于某种原因,它给出了与np.linalg.matrix_power(matrix, 3)不同的答案可能是什么问题?

看到这个:

>>> import numpy as np
>>> result = np.zeros((3, 3))
>>> result
array([[0., 0., 0.],
       [0., 0., 0.],
       [0., 0., 0.]])
>>> a = result
>>> result[1][0] += 42
>>> result
array([[ 0.,  0.,  0.],
       [42.,  0.,  0.],
       [ 0.,  0.,  0.]])
>>> a
array([[ 0.,  0.,  0.],
       [42.,  0.,  0.],
       [ 0.,  0.,  0.]])

您的代码中的问题是您没有将result复制到a并且当您稍后在循环中改变result时,您同时改变a

要制作副本,请将您的作业替换为:

a = result.copy()
def matrix_power(a, power):
    rows, columns = len(a), len(a[0])
    result = np.zeros((rows, columns))
    b = a
    for step in range(1, power):
        result = np.zeros((rows, columns)) # reset result to all zeroes matrix here
        for i in range(0, rows):
            for j in range(0, columns):
                for m in range(0, rows):
                    result[i][j] += a[i][m] * b[m][j]
        
        a = result
    for val in result:
        print(val)
    return result

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM