next up previous
Next: Predicates Up: Unit 04 Previous: Comparison operators

Comparing floating point numbers

A consequence of the rounding errors when representing or performing operations on floating point numbers is that the comparison between such numbers could produce unexpected results.

Example: Consider the following code fragment:

double r = Math.sqrt(2);   // computes the square root of 2
double d = (r * r) - 2;
System.out.println(d);     // prints 4.440892098500626E-16 instead of 0
boolean b = (d == 0);
System.out.println(b);     // prints false (we would expect true)

Hence, when comparing floating point numbers, we have to take into account the following:


next up previous
Next: Predicates Up: Unit 04 Previous: Comparison operators