Java Reference
In-Depth Information
System.out.println("3.0 / 7.0 + 2.0 / 7.0 + 2.0 / 7.0 = "
+ (3.0 / 7.0 + 2.0 / 7.0 + 2.0 / 7.0));
System.out.println("x = " + x);
System.out.println("y = " + y);
if (x == y)
System.out.println("x and y are the same.");
else
System.out.println("x and y are not the same.");
4
if (Math.abs(x - y) < 0.000001)
System.out.println("x and y are the same within the "
+ "tolerance 0.000001.");
else
System.out.println(" x and y are not the same within "
+ "the tolerance 0.000001.");
}
}
Sample Run:
3.0 / 7.0 + 2.0 / 7.0 + 2.0 / 7.0 = 0.9999999999999999
x = 1.0
y = 0.9999999999999999
x and y are not the same.
x and y are the same within the tolerance 0.000001.
In this program, x is initialized to 1.0 and y is initialized to 3.0 / 7.0 + 2.0 / 7.0 + 2.0
/ 7.0 . Now because of rounding, as shown by the output, this expression evaluates to
0.99999999999999989 . Therefore, the expression (x == y) evaluates to false . How-
ever, if you evaluate the expression 3.0 / 7.0 + 2.0 / 7.0 + 2.0 / 7.0 by hand using a
paper and a pencil, you will get 3.0 / 7.0 + 2.0 / 7.0 + 2.0 / 7.0 = (3.0 + 2.0 + 2.0) /
7.0 = 7.0 / 7.0 = 1.0 . That is, the value of y should be set to 1.0 .
The preceding program and its output show that you should be careful when comparing
floating-point numbers for equality. One way to check whether two floating-point
numbers are equal is to check whether the absolute value of their difference is less than
a certain tolerance. For example, suppose the tolerance is 0.000001 . Then x and y are
equal if the absolute value of (x - y) is less than 0.000001 . To find the absolute value, you
can use the function Math.abs of the class Math , as shown in the program. Therefore,
the expression Math.abs(x - y) < 0.000001 determines whether the absolute value of
(x - y) is less than 0.000001 .
Search WWH ::




Custom Search