I am calculating the n-th fibonacci number using (a) a linear approach, and (b) this expression
Python code:
'Different implementations for computing the n-th fibonacci number'
def lfib(n):
'Find the n-th fibonacci number iteratively'
a, b = 0, 1
for i in range(n):
a, b = b, a + b
return a
def efib(n):
'Compute the n-th fibonacci number using the formulae'
from math import sqrt, floor
x = (1 + sqrt(5))/2
return long(floor((x**n)/sqrt(5) + 0.5))
if __name__ == '__main__':
for i in range(60,80):
if lfib(i) != efib(i):
print i, "lfib:", lfib(i)
print " efib:", efib(i)
For n > 71 I see that the two functions return different values.
Is this due to floating point arithmetic involved in efib()? If so, is it then advisable to calculate the number using the matrix form?