Numpy's matrix_power function giving wrong results for large exponents [duplicate]

我怕爱的太早我们不能终老 提交于 2019-12-10 16:49:43

问题


I'm working on an implementation of the Fibonacci sequence in Numpy using the Q-Matrix method. The results are fine up till n = 47. At this point, the matrix_power function is returning incorrect results. Any explanation about why this is happening?

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

回答1:


If you are going to be playing around with the Fibonacci numbers, it is probably warranted to sacrifice some speed and use Python's arbitrarily large integers. You can do it by setting your matrix's dtype to object.

You also don't really need to use the np.matrix object, it is almost always better to stick with normal arrays. And you can extract the relevant item without converting your array to a list:

def fibonacci(n):
    qmatrix = numpy.array([[1, 1], [1, 0]], dtype=object)
    return numpy.linalg.matrix_power(qmatrix, n)[0, 1]


来源:https://stackoverflow.com/questions/41890448/numpys-matrix-power-function-giving-wrong-results-for-large-exponents

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!