Reputation: 101
I'm using binary search to write a simple square root calculator that takes in doubles in Java. When I tried to test my code by printing out the answer in the main function, however, nothing got printed out in the terminal. I also got errors Possible lossy conversion from double to float
......
Here is my code:
public class MyMath{
public static double sqrt(double n){
double u = 1;
double l = 0;
float m = (u + l) / 2;
double norm_input = 1;
float acc = 0.00000000001;
double answer = 0;
if ((n > 0) && (n < 1)){
if ((m * m) < n){
l = m;
}else{
u = m;
}
answer = (u + l) / 2;
return answer;
}else{
int count = 0;
while (n > 1){
n = n / 4;
norm_input = norm_input * 2;
count++;
}
while ((u - l) > acc){
if ((m * m) < n){
l = m;
}else{
u = m;
}
}
answer = (u + l) / 2 * norm_input;
return answer;
}
}
public static void main(String[] args){
double a = new MyMath().sqrt(4);
System.out.println(a);
}
}
Upvotes: 0
Views: 948
Reputation: 11
float m = (u + l) / 2;
Here you have to type cast into float because when two datatype variable participated in division the result would be in higher data type.
float acc = 0.00000000001;
Here also you have type cast because by default java treats a decimal point value as Double.
while ((u - l) > acc){
if ((m * m) < n){
l = m;
}
}
and your code here is going to infinite loop .
Upvotes: 1
Reputation: 688
It is stuck in infinite loop in second while condition, that's the reason it is not printing values to console.
Upvotes: 3