# Comparing floating point numbers

• Introduction

• This and the next 2 webpages will discuss a number caveats that you must be aware of when you use if-statements

• If you ignore these caveats, you may not be able to find errors that prevent your program from working correctly.

• This webpage discusses the caveat when you use floating point numbers:

• Why you must NEVER use floating point values in the equality (==) and unequality (!=) conditions.

• The second webpage discusses how to compare strings

• The third webpage discusses how to compare objects

• NEVER use double values in "==" and "!=" conditions

• Recall the problem with working with floating point values in a computer: click here

Basically, floating point values are not stored precisely

• This "round-off" error can cause the equality (==) and the unequality (!=) test to fail.

• Example: consider this program:

 ``` public class CompareDouble { public static void main(String[] args) { double r = Math.sqrt(2.0); double d = r * r - 2.0; if ( d == 0.0 ) System.out.println("sqrt(2.0)squared minus 2.0 is 0"); else System.out.println("sqrt(2.0)squared minus 2.0 is not 0 but " + d); } } ```

• By any "human" standard, the square of the square root of 2 is equal to 2...

• Hence, the difference between "the square of the square root of 2" and "2" is 0...

• But if we run this program, we find that the program will print:
```   sqrt(2.0)squared minus 2.0 is not 0 but 4.440892098500626E-16
```

Technically speaking, 4.440892098500626E-16 is NOT zero.

But, practically speaking, it is, because we must allow for a certain error threshold in floating point numbers...

(This is especially true in empirical sciences (Physics and Chemistry) when the precise values are not known; but only accurate upto a certain error value).

• Example Program: (Demo above code)

Run this program to see that above result...

• How to compare double values in "==" and "!=" conditions

• To test whether a floating value x is close to zero, we must test for:

 ``` | x | < ε ```

(The absolute value of x is less than a small threshold amount)

• Similarly, to test if 2 floating values x and y is close to each other, we must test for:

 ``` | x - y | < ε ```

(The absolute value of the difference x - y is less than a small threshold amount)

• Example: the program above re-written using the correct test

 ``` public class CompareDouble2 { public static void main(String[] args) { final double EPSILON = 1E-10; double r = Math.sqrt(2.0); double d = r * r - 2.0; if ( Math.abs(d) < EPSILON ) System.out.println("sqrt(2.0)squared nimus 2.0 is 0"); else System.out.println("sqrt(2.0)squared minus 2.0 is not 0 but " + d); } } ```

• Self Check

• Do we need to worry about round off errors in "<", ">", "<=" and ">=" conditions ?