Numpy 的 matrix_power 函数给出大指数的错误结果
Numpy's matrix_power function giving wrong results for large exponents
我正在使用 Q-Matrix method. The results are fine up till n = 47. At this point, the matrix_power
function is returning incorrect results 在 Numpy 中实现斐波那契数列。关于为什么会发生这种情况的任何解释?
import numpy
def fibonacci(n):
qmatrix = numpy.matrix([[1, 1], [1, 0]])
(a,b,c,d) = numpy.linalg.matrix_power(qmatrix,n).flatten().tolist()[0]
return b
print fibonacci(47) # Outputs -1323752223
如果您打算使用斐波那契数列,可能需要牺牲一些速度并使用 Python 的任意大整数。您可以通过将矩阵的 dtype 设置为 object
.
来实现
您也不一定真的需要使用 np.matrix
对象,坚持使用普通数组几乎总是更好。并且您可以提取相关项目而无需将数组转换为列表:
def fibonacci(n):
qmatrix = numpy.array([[1, 1], [1, 0]], dtype=object)
return numpy.linalg.matrix_power(qmatrix, n)[0, 1]
我正在使用 Q-Matrix method. The results are fine up till n = 47. At this point, the matrix_power
function is returning incorrect results 在 Numpy 中实现斐波那契数列。关于为什么会发生这种情况的任何解释?
import numpy
def fibonacci(n):
qmatrix = numpy.matrix([[1, 1], [1, 0]])
(a,b,c,d) = numpy.linalg.matrix_power(qmatrix,n).flatten().tolist()[0]
return b
print fibonacci(47) # Outputs -1323752223
如果您打算使用斐波那契数列,可能需要牺牲一些速度并使用 Python 的任意大整数。您可以通过将矩阵的 dtype 设置为 object
.
您也不一定真的需要使用 np.matrix
对象,坚持使用普通数组几乎总是更好。并且您可以提取相关项目而无需将数组转换为列表:
def fibonacci(n):
qmatrix = numpy.array([[1, 1], [1, 0]], dtype=object)
return numpy.linalg.matrix_power(qmatrix, n)[0, 1]