Java Reference
In-Depth Information
Solution
Based on what we've just discussed, you probably won't just go comparing two floats or
doubles for equality. You might expect the floating-point wrapper classes, Float and
Double , to override the equals() method, which they do. The equals() method returns
true if the two values are the same bit for bit (i.e., if and only if the numbers are the same or
are both NaN ). It returns false otherwise, including if the argument passed in is null, or if
one object is +0.0 and the other is -0.0.
If this sounds weird, remember that the complexity comes partly from the nature of doing
real number computations in the less-precise floating-point hardware, and partly from the de-
tails of the IEEE Standard 754, which specifies the floating-point functionality that Java tries
to adhere to, so that underlying floating-point processor hardware can be used even when
Java programs are being interpreted.
To actually compare floating-point numbers for equality, it is generally desirable to compare
them within some tiny range of allowable differences; this range is often regarded as a toler-
ance or as epsilon . Example 5-2 shows an equals() method you can use to do this compar-
ison, as well as comparisons on values of NaN . When run, it prints that the first two numbers
are equal within epsilon:
$ java numbers.FloatCmp
True within epsilon 1.0E-7
$
Example 5-2. FloatCmp.java
public
public class
class FloatCmp
FloatCmp {
final
final static
static double
double EPSILON = 0.0000001 ;
public
public static
static void
void main ( String [] argv ) {
double
double da = 3 * . 3333333333 ;
double
double db = 0.99999992857 ;
// Compare two numbers that are expected to be close.
iif ( da == db ) {
System . out . println ( "Java considers " + da + "==" + db );
// else compare with our own equals overload
} else
else iif ( equals ( da , db , 0.0000001 )) {
System . out . println ( "Equal within epsilon " + EPSILON );
} else
else {
Search WWH ::




Custom Search