Pella86

Bisect algorithm

Feb 3rd, 2019
160
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.12 KB | None | 0 0
  1. #include <iostream>
  2. #include <cmath>
  3.  
  4. using namespace std;
  5.  
  6. // This function if is 0 is the solutioon of sqrt(2) - n = 0
  7. double f(double n){
  8.     return sqrt(2) - n;
  9. }
  10.  
  11. // function that returns the "sign" of the value -1, 0 for 0 or, 1 for positive
  12. template <typename T> int sgn(T val) {
  13.     return (T(0) < val) - (val < T(0));
  14. }
  15.  
  16. int main()
  17. {
  18.     //------------------ user inputs --------------------------------------
  19.  
  20.     // define the search interval
  21.     double lower = 0, upper = 2.0;
  22.  
  23.     // define the tolerance
  24.     double tolerance = 0.001;
  25.  
  26.     // define the max iterations
  27.     int n_max = 15;
  28.  
  29.  
  30.     //------------------ algorithm starts --------------------------------------
  31.  
  32.     // if the algorithm is precise enough this will be true
  33.     bool result_found = false;
  34.  
  35.  
  36.  
  37.     // start by searching in the middle of the interval
  38.     double half = (upper + lower) / 2.0;
  39.  
  40.     int n_itr = 0;
  41.     while(n_itr < n_max){
  42.         // calculate the half point
  43.         double res = f(half);
  44.  
  45.         // if the half point is 0 or the half point is lower than the tolerance
  46.         // end the porgram
  47.         if(res == 0 || ((upper - lower) / 2) < tolerance ){
  48.             cout << "result: " << half << endl;
  49.             cout << "in n iterations: " << n_itr << endl;
  50.             result_found = true;
  51.             break;
  52.         }
  53.  
  54.         // check which sign is the f(c) and f(lower), if they have the same sign
  55.         // ex. f(c) > 0 and f(lower) > 0, then set the lower limit to the half
  56.         // else the uppper limit is set to half
  57.         // (alternative sign check res * f(lower) > 0)
  58.         if( sgn<double>(res) == sgn<double>(f(lower)) ){
  59.             lower = half;
  60.             half = (lower + upper) / 2;
  61.         }
  62.         else{
  63.             upper = half;
  64.             half = (lower + upper) / 2;
  65.         }
  66.  
  67.         // shows the interval getting smaller
  68.         cout << "lower: " << lower << " half: " << half <<  " upper: " << upper  << endl;
  69.  
  70.         n_itr += 1;
  71.     }
  72.  
  73.     if(!result_found){
  74.         cout << "Not enough iteration to reach the tolerance" << endl;
  75.     }
  76.  
  77.     return 0;
  78. }
Advertisement
Add Comment
Please, Sign In to add comment