Which version is more efficient in calculating the square root ?
There are 2 versions I have written to calculate square root programatically. Note reqs strictly state not using library functions ?
This is puzzling, the first method takes one extra iteration over the 2nd one but returns the more accurate answer of 3.00.
Why does it take an extra iteration ?
- So, which one is more efficient ?
- Do you find any bugs in this code ?
- When will it overflow ?
- Do both approaches seem logical, one is trying to calculate the difference between square of approximation and actual number, whereas other trying to bisect the interval. Would you pick one over the other ?
public void squareRoot()
{
double n = 9;
double epsilon = 0.001;
double guess = n*n;
double low = 0;
double high = n;
int cnt=0;
while(Math.abs(guess*guess-n)>epsilon)
{
guess = (low + high)/2;
if(guess*guess>n)
high = guess;
else
low = guess;
cnt+=1;
System.out.println("Low:"+low+"high:"+high+"guess:"+guess+"cnt:"+cnt);
}
if(guess*guess-n<epsilon)
{
System.out.println("The square root is:"+guess);
}
}
public void anotherSquareRoot()
{
double n = 9;
double epsilon = 0.001;
double guess = n*n;
double low = 0;
double high = n;
int cnt=0;
while(high-low>epsilon)
{
guess = (low + high)/2;
if(guess*guess>n)
high = guess;
else
low = guess;
cnt+=1;
System.out.println("Low:"+low+"high:"+high+"guess:"+guess+"cnt:"+cnt);
}
if(guess*guess-n<epsilon)
{
System.out.println("The square root is:"+guess);
}
}