Advertisement
vlatkovski

Binet's formula for n-th Fibonnaci number accuracy

Aug 3rd, 2018
373
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.32 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. // How good is Binet's formula for approximating the n-th Fibonacci number?
  4. // Spoilers: it's good for N <= 72
  5.  
  6. typedef long long ll;
  7. typedef long double ld;
  8.  
  9. const int MAXN = 1000;
  10.  
  11. const ld phi = 1.618033988749894848204586834365638117720309179805762862135;
  12. const ld oneoversqrt5 = 0.447213595499957939281834733746255247088123671922305144854;
  13.  
  14. ll fibdp[MAXN];
  15. ld phipow[MAXN]; // phi^n
  16. ld phipowrec[MAXN]; // 1 / (phi^n)
  17.  
  18. // Regular Fibonacci formula:
  19. // fib(0) = 0, fib(1) = 1, fib(n) = fib(n-1) + fib(n-2), for n >= 2
  20. ll fibaccurate(int n) {
  21.   return (fibdp[n] != -1) ? fibdp[n] : fibdp[n] = fibaccurate(n-1) + fibaccurate(n-2);
  22. }
  23.  
  24. // Binet's formula:
  25. // fib(n) = [ (phi^n - (-phi)^(-n)) / sqrt(5) ]
  26. // where [x] = closest integer to x
  27. ll fibapprox(int n) {
  28.   return round( oneoversqrt5 * (phipow[n] - phipowrec[n]*(n&1?-1:1)) );
  29. }
  30.  
  31.  
  32. int main() {
  33.  
  34.   memset(fibdp, -1, sizeof(fibdp));
  35.   fibdp[0] = 0;
  36.   fibdp[1] = 1;
  37.   phipow[0] = 1.0;
  38.   for (int i = 1; i < MAXN; ++i) {
  39.     phipow[i] = phipow[i-1] * phi;
  40.     phipowrec[i] = 1.0 / phipow[i];
  41.   }
  42.  
  43.   int n = 2;
  44.   ll f1, f2;
  45.   do {
  46.     f1 = fibaccurate(n);
  47.     f2 = fibapprox(n);
  48.     ++n;
  49.     cout << "n = " << setw(3) << n << " : " << setw(20) << f1 << " " << setw(20) << f2 << endl;
  50.   } while (f1 == f2 && n < MAXN);
  51.  
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement