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:

• We cannot use simply == to perform the comparison.
• Two values x and y are close to each other if | x - y|eps, where eps is a very small number (e.g., 10-14).
• If x and y are very big or very small, it is better to use eps instead. If one of the two numbers is zero, we must not divide by max(| x|,| y|).

Next: Predicates Up: Unit 04 Previous: Comparison operators