Basically, floating point values are not stored precisely
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); } } |
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).
Run this program to see that above result...
| x | < ε |
(The absolute value of x is less than a small threshold amount)
| x - y | < ε |
(The absolute value of the difference x - y is less than a small threshold amount)
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); } } |
Answer:
1.0000 < 2.000 and 1.00001 < 2.0000 are both true.