Question

Bisection is as far as i know narrowing your search and reach the specific value in interval. please give me a sample of that how to make a generic code to find square-root. the way i think is taking three variables low, mid, high. high = userinput, low = 0, mid (low + high) /2, problem is how to how to change values then.

Was it helpful?

Solution

#include <iostream>
using namespace std;

int main() {
   int val;
   cout << "Enter the number: ";
   cin >> val;

   if( val< 0) {
      cout<< "According to my maths its not possible." << endl;
   } else {
      float low = 0, high = val;
      float mid = (low  + high)/2;
      int c = 0;

      while (c != 1) {
         if(mid * mid = val) {
            cout << "Square root is: " << mid <<endl;
            c = 1;
         } else {
            if(mid * mid > val) {
               high = mid;
               mid = (low + high)/2;
            } else {
               low = mid;
               mid = (low + high)/2;
            }
         }
      }
   }
   return 0;
}

OTHER TIPS

Lets say the we are looking for sqrt(N)

As described here, you have to find the average of LOW and HIGH, if square of average is greater than N, we change the high value with the average we just found, if it is less than N, we change the low value with the average. And we repeat the steps as many times to satisfy the required precision.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top