Java Reference
In-Depth Information
}
In general, we advise to always take care with boolean predicates that use
the equality tests == since there can be numerical round-off errors. Indeed,
remember that machine computations on reals are done using single or double
precision, and thus the result may be truncated to fit the formatting of numbers.
Consider for example the following tiny example that illustrates numerical
imprecisions of programs:
class RoundOff
{ public static void main( String [ ]
arg )
double a=1.0d;
double b=3.14d;
double c=a+b ;
if ( c==4.14) // Equality tests are dangerous!
System . out . println ( "Correct" );
else
System . out . println ( "Incorrect. I branched on the wrong
block!!!" );
System . out . println ( "a=" +a+ "b=" +b+ " a+b=c=" +c ) ;
// unexpected behavior may follow...
}
}
}
Running this program, we get the surprising result caused by numerical
precision problems:
Incorrect. I branched on the wrong block!!!
a=1.0 b=3.14 a+b=c=4.140000000000001
This clearly demonstrates that equality tests == in predicates may be harmful.
2.2.4 Relational and logical operators for comparisons
The relational operators (also called comparison operators) that evaluate to
either true or false are the following ones:
 
Search WWH ::




Custom Search