What is the output of the following code?
public class Main { public static void main(String[] args) { double x = 1.0 - 0.1 - 0.1 - 0.1 - 0.1 - 0.1; System.out.println(x == 0.5); } }
false
Java floating-point numbers have a limited precision.
Calculations involving floating-point numbers can introduce round-off errors.
Equality test of two floating-point values is not reliable.
Here, x is not exactly 0.5, but is 0.5000000000000001.
We can compare whether they are close enough by testing whether the difference of the two numbers is less than some threshold.
public class Main { public static void main(String[] args) { final double EPSILON = 1E-14; double x = 1.0 - 0.1 - 0.1 - 0.1 - 0.1 - 0.1; if (Math.abs(x - 0.5) < EPSILON) System.out.println(x + " is approximately 0.5"); }/*from w w w . j a v a2 s .co m*/ }
The Math.abs(a)
method can be used to return the absolute value of a.