Advertisement
slik1977

FibonacciMethod

Mar 17th, 2022
222
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.85 KB | None | 0 0
  1. #include <algorithm>
  2. #include <iostream>
  3. #include <vector>
  4. #include <cmath>
  5. #include <exception>
  6.  
  7. int64_t fib(int64_t n)
  8. {
  9.     if (n == 0 || n == 1)
  10.         return 1;
  11.     int64_t a = 1, b = 1, res = 0;
  12.     for (int64_t i = 1; i < n; ++i)
  13.     {
  14.         res = a + b;
  15.         a = b;
  16.         b = res;
  17.     }
  18.     return res;
  19. }
  20.  
  21. double fibonacci(double a, double b, double (*f)(double x), int64_t n)
  22. {
  23.     if (a > b)
  24.         std::swap(a, b);
  25.     double lambda, mu;
  26.     int64_t fibo;
  27.     for (int64_t k = 0; k < n; ++k)
  28.     {
  29.         fibo = fib(n - k + 1);
  30.         lambda = a + (double)(fib(n - k - 1)) / fibo * (b - a);
  31.         mu = a + (double)(fib(n - k)) / fibo * (b - a);
  32.  
  33.         if (f(lambda) > f(mu))
  34.         {
  35.             a = lambda;
  36.         }
  37.         else
  38.         {
  39.             b = mu;
  40.         }
  41.     }
  42.     return (a + b) * 0.5;
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement