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.