Advertisement
ilyakanyshev

lab1 v4

Jan 19th, 2020
341
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.81 KB | None | 0 0
  1. #include <iostream>
  2. #include <math.h>
  3.  
  4. using namespace std;
  5.  
  6. double f(double x);
  7. double method_bisekcii(double start, double end, double epsil, double (*fun)(double));
  8. double method_bisekcii(double start, double end, double epsil, int &n, double (*fun)(double));
  9.  
  10. int main()
  11. {
  12.     double a, b, result1, result2, epsil;
  13.     int n = 0;
  14.     cout << "Please, enter start, end: ";
  15.     cin >> a >> b;
  16.     cout << "Enter epsil: ";
  17.     cin >> epsil;
  18.     result1 = method_bisekcii(a, b, epsil, f);
  19.     result2 = method_bisekcii(a, b, epsil, n, f);
  20.     cout << "Koren1 = " << result1 << endl;
  21.     cout << "Koren2 = " << result2 << " and n = " << n << endl;
  22.    
  23.     return 0;
  24. }
  25.  
  26. double f(double x)
  27. {
  28.     return sin(x - 2) + 0.5;
  29. }
  30.  
  31. double method_bisekcii(double start, double end, double epsil, double (*fun)(double))
  32. {
  33.     while (fabs(end-start)>epsil)
  34.     {
  35.         double center = (start+end)/2;
  36.         if (f(start) * f(center) > 0)
  37.             start = center;
  38.         else if (f(center)==0)
  39.             return center;
  40.         else
  41.             end = center;
  42.     }
  43.     return start;
  44. }
  45.  
  46. double method_bisekcii(double start, double end, int count, double (*fun)(double))
  47. {
  48.     for (int i = 0; i < count; i++)
  49.     {
  50.         double center = (start+end)/2;
  51.         if (f(start) * f(center) > 0)
  52.             start = center;
  53.         else if (f(center)==0)
  54.             return center;
  55.         else
  56.             end = center;
  57.     }
  58.     return start;
  59. }
  60. double method_bisekcii(double start, double end, double epsil, int &n, double (*fun)(double))
  61. {
  62.     double result1, result2;
  63.     n = 10;
  64.     do {
  65.         result1 = method_bisekcii(start, end, n, fun);
  66.         result2 = method_bisekcii(start, end, 2*n, fun);
  67.         n *= 2;
  68.     } while (fabs(result1 - result2) > epsil*3);
  69.     return result1;
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement