thespeedracer38

Bisection Method by AN Sir

Jan 31st, 2019
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.13 KB | None | 0 0
  1. #include <iostream>
  2. #include <cstdlib>
  3.  
  4. using namespace std;
  5.  
  6. class Bisection{
  7.     double x[10];
  8.     int n;
  9.     public:
  10.         double function1(double x1);
  11.         void bisection();
  12. };
  13.  
  14. double Bisection::function1(double x1){
  15.     double y;
  16.     //y=x1 * x1 - 3;
  17.     //y=x1*x1-2;
  18.     //y=(x1 - 1.01) * (x1 + 1.02) * (x1 - 1.03);
  19.     y=(x1-1.11)*(x1-1.12)*(x1-1.13)*(x1 + 1.14);
  20.     return y;
  21. }
  22.  
  23. void Bisection::bisection(){
  24.     double a, b, c, f1, f2, f3, ff;
  25.     double i;
  26.     int j;
  27.     a = -10;
  28.     n = 0;
  29.     f1 = function1(a);
  30.     for(i = -9.99; i <= 10; i = i + 0.01){
  31.         b = i;
  32.         f2 = function1(b);
  33.         if(f1 * f2 < 0){
  34.             do{
  35.                 c = (a + b) / 2;
  36.                 f3 = function1(c);
  37.                 if(f1 * f3 < 0){
  38.                     b = c;
  39.                     f2 = function1(b);
  40.                 }
  41.                 else if(f2*f3 < 0){
  42.                     a = c;
  43.                     f1 = function1(a);
  44.                 }
  45.                 if(f3 < 0)
  46.                     ff = -f3;
  47.                 else
  48.                     ff = f3;
  49.                    
  50.                 if(ff < 1e-10){
  51.                     x[n++] = c;
  52.                     break;
  53.                 }
  54.             }
  55.             while(true);
  56.         }
  57.         a = i;
  58.         f1 = function1(a);
  59.     }
  60.     //To display roots
  61.     for(j = 0; j < n; j++){
  62.         cout << "Root[" << j << "]=" << x[j] << endl;
  63.     }
  64. }
  65.  
  66. int main(){
  67.     system("cls");
  68.     Bisection B;
  69.     B.bisection();
  70.     return 0;
  71. }
Add Comment
Please, Sign In to add comment