I am trying to work on a function which takes in a value n
and outputs the nth
number in the Fibonacci sequence. I have a looping function which seems to work like so:
def fibonacci_v1(n):
a = b = 1
for _ in range(1, n):
a, b = b, a + b
return a
and I am trying to work on a version which uses Binet's Formula as describes here:
Phi = (1 + math.sqrt(5)) / 2
def fibonacci_v2(n):
c = pow(Phi, n)
return math.floor((c - pow(-1, n) / c) / math.sqrt(5))
which seems to work for low values of n
but breaks when a number is entered which is higher than 72... I suspect that this has to do with the accuracy of the math.sqrt()
function but the documentation here doesn't say anything about its level of accuracy... is it the case that this is an issue with math.sqrt
or is there something else wrong with my function?
For testing purposes I was using this for loop:
for x in range(1, 73):
print(fibonacci_v1(x))
print(fibonacci_v2(x))