Advertisement
SAJID_07

Bisection Method

Feb 23rd, 2020
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.07 KB | None | 0 0
  1. // C++ program for implementation of Bisection Method for
  2. // solving equations
  3. #include<bits/stdc++.h>
  4. using namespace std;
  5. #define EPSILON 0.01
  6.  
  7. // An example function whose solution is determined using
  8. // Bisection Method. The function is x^3 - x^2 + 2
  9. double func(double x)
  10. {
  11.     return x*x*x - x*x + 2;
  12. }
  13.  
  14. // Prints root of func(x) with error of EPSILON
  15. void bisection(double a, double b)
  16. {
  17.     if (func(a) * func(b) >= 0)
  18.     {
  19.         cout << "You have not assumed right a and b\n";
  20.         return;
  21.     }
  22.  
  23.     double c = a;
  24.     while ((b-a) >= EPSILON)
  25.     {
  26.         // Find middle point
  27.         c = (a+b)/2;
  28.  
  29.         // Check if middle point is root
  30.         if (func(c) == 0.0)
  31.             break;
  32.  
  33.         // Decide the side to repeat the steps
  34.         else if (func(c)*func(a) < 0)
  35.             b = c;
  36.         else
  37.             a = c;
  38.     }
  39.     cout << "The value of root is : " << c;
  40. }
  41.  
  42. // Driver program to test above function
  43. int main()
  44. {
  45.     // Initial values assumed
  46.     double a =-200, b = 300;
  47.     bisection(a, b);
  48.     return 0;
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement