The floating point number 4 is not exactly equal to 4 It can be: 4.000000000000000001 Or: 3.999999999999999999 |
|
Consequently:
4.00000000000001 != 3.9999999999999 |
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 |
|
|
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"); } } } |
You can modify the test as follows:
if ( Math.abs( b - a ) < ( 0.00000001 * (Math.abs(b) + Math.abs(a)) ) ) { ... } |