-5

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.

Jhon Smith
  • 21
  • 1
  • 1
  • 2

2 Answers2

5
#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;
}
Cloud
  • 18,753
  • 15
  • 79
  • 153
Ahsan S. Sher
  • 108
  • 1
  • 2
  • 9
  • @user2966111 Please make an effort to really understand why this works. You won't ever be successfull in your class if you just copy paste the solution. – stefan Nov 07 '13 at 19:32
  • what the explanation behind "c=0" and "while (c != 1)"? – sugab Feb 23 '15 at 09:24
  • c=0 is initial condition and c!=1 is to check condition, while it's true it will exit the loop ( c=1) – sugab Mar 01 '15 at 06:40
  • For not perfect square root the loop will run for ever! – antonjs Jul 05 '17 at 10:16
0

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.

Etherealone
  • 3,488
  • 2
  • 37
  • 56