This code is working fine but when i tried the same code in other language I am getting answer upto more decimal places.
public class SquareRoot {
public static double getSqRoot(int num, int decimal_place){
int mid = 0;
double ans = 0;
int start = 0;
int end = num;
while (start<=end){
mid = (start+end)/2;
if (mid *mid ==num)
{
ans=mid;
break;
}
if (mid *mid < num)
{
start=mid+1;
ans=mid;
}else {
end=mid-1;
}
}
// fractional part
double inc = 0.1;
for (int i = 0; i < decimal_place; i++) {
while (ans*ans <= num){
ans = ans + inc;
}
// ans*ans > num
ans = ans-inc;
inc = inc/10;
}
return ans;
}
public static void main(String[] args) {
System.out.println(getSqRoot(10, 3)); //3.1619999999999986
System.out.println(getSqRoot(9, 3));
}
}