Facebook
From Obese Lechwe, 5 Years ago, written in Plain Text.
Embed
Download Paste or View Raw
Hits: 194
  1. #define _CRT_SECURE_NO_WARNINGS
  2. #define ACCURACY  0.01
  3.  
  4. #include <iostream>
  5. #include <math.h>
  6.  
  7. unsigned int iterations = 0;
  8. volatile double         y_a,    y_b,    a,      b;
  9. volatile double         y_x1,   y_x2,   x1,     x2;
  10.  
  11. double funct(double x)
  12. {
  13.         double _return = x/(1.2 - sin(2*x));
  14.  
  15.         return _return;
  16. }
  17.  
  18.  
  19. double calc_point1()
  20. {
  21.         x1 = (a + b)/3;
  22.         iterations++;
  23.  
  24.         return x1;
  25. }
  26.  
  27. double calc_point2()
  28. {
  29.         x2 = ((a + b) * 2)/3;
  30.         iterations++;
  31.  
  32.         return x2;
  33. }
  34.  
  35. void calc_limits(double _x1, double _x2)
  36. {
  37.         a = funct(_x1);
  38.         b = funct(_x2);
  39. }
  40.  
  41. void calc_internals(double _x1, double _x2)
  42. {
  43.         y_x1 = funct(_x1);
  44.         y_x2 = funct(_x2);
  45. }
  46.  
  47. void calc()
  48. {
  49.         while ((b-a) > ACCURACY)
  50.         {
  51.                 calc_internals(calc_point1(), calc_point2());
  52.  
  53.                 if (y_x1 >= y_x2)
  54.                 {
  55.                         a = x1;
  56.                 }
  57.  
  58.                 else if (y_x1 < y_x2)
  59.                 {
  60.                         b = x2;
  61.                 }
  62.         }
  63. }
  64.  
  65.  
  66. int main()
  67. {
  68.         calc_limits(1.0, 4.2);
  69.         calc();
  70.         std::cout << "Iterations: " << iterations << std::endl;
  71.         std::cout << "Minimum: " << (a+b)/2 << " " << funct((a+b)/2) << std::endl;
  72.         getchar();
  73.         return 0;
  74. }
  75.  
  76.