What is the output of the following snippet?
public class test {
public static void main(String[] args) {
double a = 1.3378901234567877;
double b = 0.0008901234567876;
double c = a - b;
if (c == 1.337) {
System.out.println("Hallo doubles!");
} else {
System.out.println("Oh no! Comparison failed!");
}
}
}
. . . . . . . . . . . . . . . . .
Solution
Oh no! Comparison failed!
Explanation
Doubles are internally represented using the IEEE 754 standard (source). This means, doubles are not represented with arbitrary precision.
Just execute this snippet:
public class test {
public static void main(String[] args) {
double a = 1.3378901234567876;
System.out.println("a = " + a);
double b = 0.0008901234567876;
System.out.println("b = " + b);
double c = a - b;
System.out.println("c = " + c);
}
}
Output:
a = 1.3378901234567877
b = 8.901234567876E-4
c = 1.3370000000000002
Resolve problem
Use an appropriate epsilon to compare floats/doubles:
public class test {
public static void main(String[] args) {
double a = 1.3378901234567877;
double b = 0.0008901234567876;
double c = a - b;
double EPSILON = 0.000000000000001;
if (Math.abs(c - 1.337) < EPSILON) {
System.out.println("Hallo doubles!");
} else {
System.out.println("Oh no! Comparison failed!");
}
}
}