rafid_shad

Bisection method

Nov 23rd, 2019
242
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.66 KB | None | 0 0
  1. // Bisection Method for the function is x^3 - x -1
  2.  
  3. #include<bits/stdc++.h>
  4. using namespace std;
  5. double func(double x)
  6. {
  7.     return x*x*x - x-1;
  8. }
  9. void bisection(double a, double b)
  10. {
  11.     if (func(a) * func(b) >= 0)
  12.     {
  13.         cout << "You didn't took right a and b"<<endl;
  14.         return;
  15.     }
  16.  
  17.     double c;
  18.     while (abs(b-a) >= 0.01)
  19.     {
  20.         // Find middle point
  21.         c = (a+b)/2;
  22.         if (func(c)< 0)
  23.             b = c;
  24.         else
  25.             a = c;
  26.     }
  27.     cout << "The value of root is : " << c<<endl;
  28. }
  29. int main()
  30. {
  31.     // Initial values for a and b
  32.     double b =1, a = 2;
  33.     bisection(a, b);
  34.     return 0;
  35. }
Advertisement
Add Comment
Please, Sign In to add comment