I’m try to write a fast fibonacci algorithm in python that can be used for extremely large values, but I keep getting negative values, so I’m assuming its not properly using longs?
fibonacci_matrix = numpy.matrix([[1,1],[1,0]])
def fib(n):
return (fibonacci_matrix**(n-1)) [0,0]
fibonacci_matrix2 = numpy.matrix([[1L,1L],[1L,0L]])
def fib2(n):
return (fibonacci_matrix2**(n-1)) [0,0]
def fib3(n):
if n in [1,2]:
return 1L
else:
return long(long(fib2(n-1))+long(fib2(n-2)))
print fib(47)
print fib2(93)
print fib3(95)
Which gives me output:
-1323752223
-6246583658587674878
-4953053512429003327
instead of positive values like all fibonacci numbers should be.
Can someone help troubleshoot this? Or better yet help me write an improved, efficient and infinetly accurate fibonnaci sequence code? Most of my googling yields terrible basic slow recursive fibonnacci algorithms.
You can make numpy use Python arbitrary-precision integers by setting the dtype to object:
but I don’t know how much that will help. Usually if you want a really fast implementation of some recursive function like this, you use the various identities to do reductions. For example, using the identity F(2*n) = F(n+1)^2-F(n-1)^2 allows a nice logarithmic evaluation. [Actually, Wikipedia lists a generalization of this which is even better.]
Is there some reason you really need speed?