StoneHaos

nastya_mod1

Mar 1st, 2021 (edited)
549
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <utility>
  2. #include <math.h>
  3. #include <iostream>
  4.  
  5. using namespace std;
  6.  
  7. double dx = 0.001;
  8.  
  9. double f(double x)
  10. {
  11.     return pow(x, 2.0 / 3) - x;
  12. }
  13.  
  14. pair<double, double> F1(double x0, double h)
  15. {
  16.     int k = 1;
  17.     double x1, x2;
  18.     if (f(x0 - h) <= f(x0) && f(x0) <= f(x0 + h))
  19.     {
  20.         x1 = x0 + h;
  21.     }
  22.     else if (f(x0 - h) >= f(x0) && f(x0) >= f(x0 + h))
  23.     {
  24.         x1 = x0 - h;
  25.         h = -h;
  26.     }
  27.     else
  28.     {
  29.         return pair<double, double>((x0 - h < 0) ? 0 : x0 - h, x0 + h);
  30.     }
  31.  
  32.     x2 = x1;
  33.     x1 = x0;
  34.     do
  35.     {
  36.         x0 = x1;
  37.         x1 = x2;
  38.         x2 = x1 + pow(2.0, k * 1.0) * h;
  39.         k++;
  40.     } while (f(x2) >= f(x1));
  41.  
  42.     if (h > 0)
  43.     {
  44.         return pair<double, double>(x0 < 0 ? 0 : x0, x2);
  45.     }
  46.     else
  47.     {
  48.         return pair<double, double>(x2 < 0 ? 0 : x2, x0);
  49.     }
  50. }
  51.  
  52. double fp1(double x)
  53. {
  54.     return (f(x + dx) - f(x)) / dx;
  55. }
  56.  
  57. double fp2(double x)
  58. {
  59.     return (fp1(x + dx) - fp1(x)) / dx;
  60. }
  61.  
  62. double F2(pair<double, double> sv, double e)
  63. {
  64.     double x0, x1 = sv.first;
  65.     do
  66.     {
  67.         x0 = x1;
  68.         x1 = x0 - fp1(x0) / fp2(x0);
  69.     } while (abs(x1 - x0) > e);
  70.     return x1;
  71. }
  72.  
  73. int main()
  74. {
  75.     pair<double, double> a = F1(-100, 0.0001);
  76.     double x = F2(a, 0.001);
  77.     cout << "max = f(" << x << ") = " << f(x) << endl;
  78.     return 0;
  79. }
RAW Paste Data