Advertisement
Infiniti_Inter

"Золотое" сечение

Oct 7th, 2020
602
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.08 KB | None | 0 0
  1. #define _CRT_SECURE_NO_WARNINGS
  2. #include<iostream>
  3. #include<string>
  4. #include<alg.h>
  5.  
  6. using namespace std;
  7. const double EPS = 1e-4;
  8. const double DELTA = 1e-5;
  9. const int INF = 1e8 + 13;
  10. const double goldenRatio1 = (3 - sqrt(5)) / 2; // "Золотое" число
  11. const double goldenRatio2 = (sqrt(5) - 1) / 2; // "Золотое" число
  12.  
  13. double func(double x)
  14. {
  15.     return 2. * x*x - 6 * x - 3;
  16. }
  17.  
  18. pair<double, double> solve()
  19. {
  20.  
  21.     double left = -1;
  22.     double right = 3;
  23.     double step = 0.1;
  24.     double answer = INF;
  25.     double answerPoint = -INF;
  26.    
  27.     double x1, x2;
  28.     while (fabs(right - left) > EPS) {
  29.         x1 = left + goldenRatio1*(right - left);
  30.         x2 = left + goldenRatio2*(right - left);
  31.         if (func(x1) >= func(x2))
  32.             left = x1;
  33.         else
  34.             right = x2;
  35.     }
  36.     answer = func((left + right) / 2);
  37.     answerPoint = (left + right) / 2;
  38.     return make_pair(answer, answerPoint);
  39. }
  40.  
  41. int main()
  42. {
  43.     freopen("input.txt", "r", stdin);
  44.     freopen("output.txt", "w", stdout);
  45.  
  46.     pair<double, double> ans = solve();
  47.     cout << "min = " << ans.first << "\nwith x =  " << ans.second << endl;
  48.  
  49. }
  50.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement