I wanted to use NumPy
in a Fibonacci question because of its efficiency in matrix multiplication. You know that there is a method for finding Fibonacci numbers with the matrix [[1, 1], [1, 0]]
.
I wrote some very simple code but after increasing n
, the matrix is starting to give negative numbers.
import numpy
def fib(n):
return (numpy.matrix("1 1; 1 0")**n).item(1)
print fib(90)
# Gives -1581614984
What could be the reason for this?
Note: linalg.matrix_power
also gives negative values.
Note2: I tried numbers from 0 to 100. It starts to give negative values after 47. Is it a large integer issue because NumPy is coded in C ? If so, how could I solve this ?
Edit: Using regular python list
matrix with linalg.matrix_power
also gave negative results. Also let me add that not all results are negative after 47, it occurs randomly.
Edit2: I tried using the method @AlbertoGarcia-Raboso suggested. It resolved the negative number problem, however another issues occured. It gives the answer as -5.168070885485832e+19
where I need -51680708854858323072L
. So I tried using int()
, it converted it to L
, but now it seems the answer is incorrect because of a loss in precision.