This code sample contains methods to find a square root of both perfect and non perfect squares using java.
{
public static void main(String[] args)
{
SquareRoot sR = new SquareRoot();
System.out.println("Square Root of 100 -> " + sR.getPerfectSquareRoot(100));
System.out.println("Square Root of 51 -> " + sR.getSquareRoot(51, 0.025f));
}
public float getPerfectSquareRoot(int num)
{
return getSquareRoot(num, 0.0f);
}
public float getSquareRoot(int num, float errorFactor)
{
float r = 0;
float x = num / 2;
float sqr = 0;
while (true)
{
sqr = x * x;
if (sqr == num)
{
return x;
}
else if ((num > sqr && num < sqr + errorFactor) || (num < sqr && num > sqr - errorFactor)) // / error factor
// is 0.25
{
return x;
}
else
{
r = num / x;
x = (r + x) / 2;
}
}
}
}