Numpy's matrix_power function giving wrong res

2019-06-24 04:58发布

问题:

This question already has an answer here:

  • Numpy matrix exponentiation gives negative value 1 answer

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]