1
from math import sqrt

n = int(input())
phi = (1 + sqrt(5))/2

fib_n = round((phi**n))

print(fib_n)

The above-mentioned code is not correct, it gives some nearer value to fib_n.

from math import sqrt

n = int(input())
phi = (1 + sqrt(5))/2

fib_n = round((phi**n)/sqrt(5))

print(fib_n)

This code works absolutely perfect after dividing by sqrt(5) in the 6th line.

My doubts are:

  1. What is the significance of dividing by sqrt(5) and why only sqrt(5) and not any other number?
  2. Can I solve the same thing using the floor or ceiling (or any other) and without dividing by root(5)?

Any help/guidance/resources are heavily appreciated!

hack3r-0m
  • 700
  • 6
  • 20

1 Answers1

1

This is the wrong formula. The formula should be:

from math import sqrt

n = int(input())
phi1 = (1 + sqrt(5))/2
phi2 = (1 - sqrt(5))/2

fib_n = (pow(phi1, n) - pow(phi2, n)) / sqrt(5)

print(fib_n) 

The sqrt(5) comes out of the proof: Proof Basically, the sqrt(5) comes from solving the partial fractions

Side note: pow(phi, n) is usually more efficient than phi ** n and it can also compute mods. pow(phi, n, m) gives (phi ** n) % m

mattyx17
  • 806
  • 6
  • 11
  • 1
    +1 What you give is the correct mathematical formula. However, note that pow(phi2, n) is very close to 0 as n gets larger, so that's why approximating it using round(pow(phi1, n))/sqrt(5) will give you the correct results too for larger n. And that happens to give correct results for smaller n as well, so in practice, that can be used. See the [proof](https://en.wikipedia.org/wiki/Fibonacci_number#Computation_by_rounding). And since OP mentioned Binet formula, the rounding version is what the OP is looking for. – justhalf May 13 '20 at 12:42
  • @justhalf @mattyx17 does ```(phi**n)/sqrt(5)``` always give correct answer? because of its showing deviation for n > = 71. – hack3r-0m May 15 '20 at 07:58
  • @hack3r_0m `(phi**n)/sqrt(5)` is an approximation. The correct mathematical formula is `((((1 + sqrt(5))/2) ** n) + (((1 - sqrt(5))/2)**n)) / sqrt(5)`. As @justhalf mentioned, ((1-sqrt(5))/2)**n goes to 0 as n gets large so in some cases is ignored – mattyx17 May 15 '20 at 14:36