Advertisement
SeriousVenom

MethodMath

Feb 25th, 2021
729
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.03 KB | None | 0 0
  1. #include <iostream>
  2. #include <cmath>
  3. #include <math.h>
  4.  
  5. using namespace std;
  6.  
  7. double MethodHalf();
  8. double SimpleIteration();
  9. double function(double x);
  10.  
  11. int main()
  12. {
  13.     int menu = 0;
  14.     cout << "Methods:\n1.Half-division Method\n2.Simple Iteration Method\nChoice: "; cin >> menu;
  15.     if (menu == 1) { MethodHalf(); }
  16.     if (menu == 2) { SimpleIteration(); }
  17.    
  18.  
  19.     return 0;
  20. }
  21.  
  22. double function(double x)
  23. {
  24.     return pow(x, 3) + 3 * x + 1;
  25. }
  26.  
  27. double MethodHalf()
  28. {
  29.     int n = 0;
  30.     double a = 0, b = 0, eps = 0, c = 0;
  31.     cout << "~~~~Half Division Method~~~~" << endl;
  32.     cout << "Enter left border: "; cin >> a;
  33.     cout << "Enter right border: "; cin >> b;
  34.     if (function(a) * function(b) > 0)
  35.     {
  36.         cout << "#Error# Wrong interval\n";
  37.         return 0;
  38.     }
  39.     cout << "Enter eps: "; cin >> eps; cout << endl;
  40.     cout << "Left border: " << a << " || Right border: " << b << " || Eps: " << eps << endl;
  41.     cout << "Equation: x^3 + 3*x + 1 = 0\n";
  42.  
  43.     do
  44.     {
  45.         c = (a + b) / 2;
  46.         if (function(c) * function(a) <= 0) b = c;
  47.         else a = c;
  48.         n += 1;
  49.     } while (fabs(a - b) >= eps);
  50.  
  51.     cout << "\n~~~~Result~~~~\n";
  52.     cout << "Root of the equation: " << c << endl;
  53.     cout << "Number of iteration: " << n << endl;
  54.     cout << "Checking the resulting root: " << function(c) << endl;
  55. }
  56.  
  57. double SimpleIteration()
  58. {
  59.     int n = 0;
  60.     double a = 0, b = 0, eps = 0, c = 0, x1 = 0, x0 = 0;
  61.     cout << "~~~~Simple Iteration Method~~~~" << endl;
  62.     cout << "Enter left border: "; cin >> a;
  63.     cout << "Enter right border: "; cin >> b;
  64.     cout << "Enter eps: "; cin >> eps; cout << endl;
  65.     cout << "Enter X1: "; cin >> x1; cout << endl;
  66.     cout << "Left border: " << a << " || Right border: " << b << " || Eps: " << eps << endl;
  67.     cout << "Equation: x^3 + 3*x + 1 = 0\n";
  68.  
  69.     //c = (a + b) / 2;
  70.     do
  71.     {
  72.         n++;
  73.         x0 = x1;
  74.         x1 = function(x0);
  75.  
  76.     } while (fabs(x1 - x0) <= eps);
  77.  
  78.     cout << "\n~~~~Result~~~~\n";
  79.     cout << "Root of the equation: " << c << endl;
  80.     cout << "Number of iteration: " << n << endl;
  81.     cout << "Checking the resulting root: " << function(c) << endl;
  82.     return 0;
  83. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement