Advertisement
slik1977

ParabolaMethod

Mar 17th, 2022
253
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.08 KB | None | 0 0
  1. #include <algorithm>
  2. #include <iostream>
  3. #include <vector>
  4. #include <cmath>
  5. #include <exception>
  6. double parab(double x1, double f1, double x2, double f2, double x3, double f3)
  7. {
  8.     return x2 - ((x2 - x1) * (x2 - x1) * (f2 - f3) - (x2 - x3) * (x2 - x3) * (f2 - f1)) / (2 * ((x2 - x1) * (f2 - f3) - (x2 - x3) * (f2 - f1)));
  9. }
  10.  
  11. double  parabola(double a, double b, double (*f)(double x), int64_t n, double eps)
  12. {
  13.     if (a > b)
  14.         std::swap(a, b);
  15.     double e = (a + b) * 0.5;
  16.     double x = (a + b) * 0.5;
  17.     double res = x;
  18.     double incor = b + 1;
  19.     double c, d;
  20.     for (int64_t i = 0; i < n; ++i)
  21.     {
  22.         res = parab(a, f(a), e, f(e), b, f(b));
  23.         if (!(res >= a && res <= b))
  24.             throw std::invalid_argument("Can't find min");
  25.         if (abs(res - x) < eps)
  26.             return res;
  27.         x = res;
  28.         c = std::min(e, x);
  29.         d = std::max(e, x);
  30.         if (f(c) < f(d))
  31.         {
  32.             b = d;
  33.             e = c;
  34.         }
  35.         else
  36.         {
  37.             a = c;
  38.             e = d;
  39.         }
  40.     }
  41.  
  42.     return res;
  43. }
  44.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement