I'm working on making a method that will calculate the square root of a supplied integer without using Math.sqrt()
. I believe everything is working except for meeting the condition of the while loop.
As of right now perfect squares will work however non perfect squares seem to loop infinitely. I'm not sure how to get it meet the conditions of the loop to break and find the square root of a non perfect square to a precision of .000001
.
public static double findSquareRoot(int value)
{
value = Math.abs(value);
double mid = value / 2.0, answer = 0;
// loop until sqrt is found
while (answer * answer != value)
{
// if middle value is sqrt
if (mid * mid == value)
{
return mid;
}
// if middle value is too big to be sqrt
else if (mid * mid > value)
{
mid = mid / 2.0;
answer = mid;
}
// if middle value is too small to be sqrt
else
{
mid = (mid + value) / 2.0;
answer = mid;
}
}
return answer;
}