### Comparing floating point values on equality (and inequality)

• Round off errors in floating point values

• From your experience with woring with calculators, you know that:

 ``` The floating point number 4 is not exactly equal to 4 It can be: 4.000000000000000001 Or: 3.999999999999999999 ```

• Comparing floating point value on equality

• When are 2 values equal to each other:

 Two values are equal if they are equal in all digits

Consequently:

 ``` 4.00000000000001 != 3.9999999999999 ```

• Example:

 ``` public class FloatEq1 { public static void main(String[] args) { double a, b; int i; a = 4.0; b = 4.0/7.0 + 4.0/7.0 + 4.0/7.0 + 4.0/7.0 + 4.0/7.0 + 4.0/7.0 + 4.0/7.0; System.out.println("a = " + a); System.out.println("b = " + b); if ( a == b ) { System.out.println("a is equal to b"); } else { System.out.println("a is NOT equal to b"); } } } ```

Output:

 ``` a = 4.0 b = 3.999999999999999 a is NOT equal to b ```

• However:

 In most applications, 4.0 is equal to 3.999999999999999 Because in the level of error tolerance in most applications is much higher than 0.000000000000001 part in 4 !!!

• Example Program: (Demo above code)

• Testing equality within a given tolerance

• Programming trick:

• When we want to test if 2 values a and b are approximately equal to each other, we use this test:

 ``` if ( absoluteValue( b − a ) < some-very-small-value ) { a and b are equal } else { a and b are not equal (too far apart) } ```

• To compute the absolute value, you can use the Math.abs() method.

• Example:

 ``` public class FloatEq2 { public static void main(String[] args) { double a, b; int i; a = 4.0; b = 4.0/7.0 + 4.0/7.0 + 4.0/7.0 + 4.0/7.0 + 4.0/7.0 + 4.0/7.0 + 4.0/7.0; System.out.println("a = " + a); System.out.println("b = " + b); if ( Math.abs( b - a ) < 0.000000001 ) { System.out.println("a is (approximately) equal to b"); } else { System.out.println("a is NOT (approximately) equal to b"); } } } ```

• Final note

• In Physics and Chemistry, they work with relative errors

You can modify the test as follows:

 ``` if ( Math.abs( b - a ) < ( 0.00000001 * (Math.abs(b) + Math.abs(a)) ) ) { ... } ```