Help with looping my function

How do I loop this function I made where it keeps guessing the square root of a number? The one after I check if the number is greater than 0

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
double root(double x){
       double y, y1 = 0, y2 = x+1;
       if(x < 0) 
            cout << "Unable to Square Root negative Number";
       else
           y = y1+y2/2;
           if(y2>x){
                 y2=y;
                 }
           if(y*y-x <= 0.0001 && y*y-x >= -0.0001){
                 return y;
                 }
           else{
                 y1=y;
                 }
           y = y1+y2/2;
}
}
This function is broken. I can't even really say what it's trying to do.
I assume you want to use http://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method
In that case, you need a sing variable guess initialized to something other than 0. Your entire code (except for checking if x < 0) would be
while |guess*guess-x| > epsilon do
   guess = (guess + x/guess)/2
Topic archived. No new replies allowed.