Java Reference
In-Depth Information
2
Even though the laws of mathematics tell us that
(
2
ɨ 2 equals 0, this program
fragment prints
sqrt(2) squared minus 2 is not 0 but
4.440892098500626E-16
Unfortunately, such roundoff errors are unavoidable. It plainly does not make sense
in most circumstances to compare floating-point numbers exactly. Instead, test
whether they are close enough.
To test whether a number x is close to zero, you can test whether the absolute value
|x| (that is, the number with its sign removed) is less than a very small threshold
number. That threshold value is often called Ə (the Greek letter epsilon). It is
common to set Ə to 10 ɨ14 when testing double numbers.
When comparing floating-point numbers, don't test for equality. Instead, check
whether they are close enough.
Similarly, you can test whether two numbers are approximately equal by checking
whether their difference is close to 0.
| x ɨ y | ʎ Ǖ
In Java, we program the test as follows:
final double EPSILON = 1E-14;
if (Math.abs(x - y) <= EPSILON)
// x is approximately equal to y
5.2.3 Comparing Strings
To test whether two strings are equal to each other, you must use the method called
equals :
if (string1. equals(string2)) . . .
Do not use the == operator to compare strings. Use the equals method instead.
Search WWH ::




Custom Search