【问题标题】:How can I use numpy.linalg.matrix_power in python to raise a matrix to a large power?如何在 python 中使用 numpy.linalg.matrix_power 将矩阵提高到大功率?
【发布时间】:2015-03-31 08:07:05
【问题描述】:

我正在尝试在 python/numpy 中将矩阵提升到高功率。似乎对于大指数,结果不正确(某种溢出?),高于 10000。这是 numpy.linalg.matrix_power 函数的已知行为还是我遗漏了什么? 这是我尝试输出的代码:

import numpy as np
from numpy import linalg as LA
A = np.array([1L,1L,1L,0L]).reshape(2,2)
print 'A: %s'%A
print 'A^10: %s'%LA.matrix_power(A,10)
print 'A^1000: %s'%LA.matrix_power(A,1000)
print 'A^10000: %s'%LA.matrix_power(A,10000)

输出:

A: 
[[1 1]
 [1 0]]
A^10: 
[[89 55]
 [55 34]]
A^1000: 
[[9079565065540428013 817770325994397771]
 [817770325994397771 8261794739546030242]]
A^10000: 
[[-83367563645688771 -2872092127636481573]
 [-2872092127636481573 2788724563990792802]]

【问题讨论】:

    标签: python numpy matrix scipy linear-algebra


    【解决方案1】:

    您已超出 64 位整数可表示的最大值。你可以试试这个:

    A = np.array([1L,1L,1L,0L], dtype=float).reshape(2,2)
    

    但是请注意,当您将A 提高到 10000 次方时,它会给您无穷大。至少这比负数要好。

    如果您确实需要完成此数学运算,则可能必须改用多精度算术(请参阅下面 Jaime 的精彩评论)。

    【讨论】:

    • np.linalg.matrix_power 使用二进制求幂来计算最终结果(纯 Python 源代码是 here),因此它只是对 np.dot 的智能调用序列。如果数组是object dtype,np.dot 使用对象__mul____add__ 方法。因此,对于 OP 的用例,只需设置 A = np.array([1, 1, 1, 0], dtype=object).reshape(2, 2) 即可利用 Python 的任意精度整数并且永远不会溢出。
    • 谢谢大家,是的,关键是通过指定 dtype=object 来利用 python 任意精度整数:A = np.array([1,1,1,0],dtype=object)。 reshape(2,2) 请更新答案,以便我接受。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-05
    • 1970-01-01
    • 1970-01-01
    • 2011-03-17
    相关资源
    最近更新 更多