Numpy 2D Array - Power Of - 没有回复?

时间:2017-02-01 13:03:36

标签: python arrays numpy matrix

我试图获得权力'使用numpy的Python列表/矩阵我目前唯一的工作解决方案是使用np.dot()的迭代函数:

def matr_power(matrix, power):
    matrix_a = list(matrix)
    matrix_b = list(matrix)
    for i in range(0, power-1):
        matrix_a = np.dot(matrix_a, matrix_b)
    return matrix_a

可以根据我的需要运行,但我知道它可能不是最有效的方法。

我尝试将我的列表转换为numpy数组,对其执行电源操作,然后返回列表,以便以我需要的形式使用它。转换似乎发生了,但功率计算没有。

while (foo != bar):
    matr_x = np.asarray(matr_a)
    matr_y = matr_x ** n
    matr_out = matr_y.tolist()
    n += 1
    # Other code here to output certain results

问题是,矩阵按预期转换为数组,但在执行电源操作时(**matr_y最终与matr_x相同,就像没有计算一样曾经表演过。我尝试使用np.power(matr_y, n)以及Stack Overflow上相关问题中的其他解决方案。

我尝试过使用numpy文档,但是(或者我误解了它,或者)它只是确认这应该按预期工作。

当检查PyCharm中的调试控制台时,一切似乎都很好(所有矩阵/列表/数组都按预期转换),但计算matr_x ** i似乎从未计算过(或者从未存储在matr_y中)。

答案

尽管可以在**运算符中使用numpy矩阵,但最好的解决方案是使用numpy数组(不推荐使用numpy矩阵)和numpy的linalg matrix_power方法。

matr_x = np.array(mat_a)
matr_y = np.linalg.matrix_power(matr_x, path_length)
work_matr = matr_y.tolist()

现在很明显,如果我没有使用邻接矩阵(只有0和1),那么**在元素方面的功能可能已被发现。

2 个答案:

答案 0 :(得分:1)

有(至少)两个选项可以使用numpy来计算矩阵的功效而无需多次调用struct s_block *create_block(size_t size, unsigned int stack) { struct s_block *block; block = sbrk(sizeof(s_block)); block->start = sbrk(stack); block->size = stack; block->end = sbrk(0); block->next = set_free_space(size, block); block->size -= size; block->next->prev = block; block->prev = NULL; return (block->next); } struct s_block *set_free_space(size_t size, struct s_block *block) { struct s_block new_block; new_block = sbrk(sizeof(s_block)); new_block->start = block->start; new_block->next = NULL; new_block->size = size; new_block->end = ???; // this is where I want to split the first sbrk // I tried new_block->end = new_block->start + size; but it doesn't work either block->start = new_block->end + 1; // and i set the new start of the big block at the end of the one i use return (new_block); }

例如,

**

答案 1 :(得分:1)

沃伦的回答非常好。

根据OP的特殊要求,我将简要解释如何手动构建一个有效的整数幂运算符。

我不知道这个算法叫什么,但它的工作原理如下: 假设您要计算X ^ 35。如果你天真地这样做,将花费你34次乘法。但你可以做得更好。写X ^ 35 = X ^ 32 x X ^ 2 x X.你在这里做的是根据35的二进制表示法分割产品,即100011.现在,计算X ^ 32实际上是便宜的,因为你只需要反复(5次)平方X即可到达那里。所以总共需要7次乘法,比34次要好得多。

在代码中:

def my_power(x, n):
    out = None
    p = x
    while True:
        if n % 2 == 1:
            if out is None:
                out = p
            else:
                out = out @ p # this requires a fairly up-to-date python
                              # if yours is too old use np.dot instead
            if n == 1:
                return out
        n //= 2
        p = p @ p