In my old knowledge : when we want to check if double or float is equal to 0.0,
we should not write like this:
double x = 0.0; if (x == 0.0) System.out.println("yes"); else System.out.println("no");
But a few minutes ago I tried again, in Java (1.7) and C ++ (Apple LLVM version 6.0) , there is no problem writing this! I tried using the double and float type under Java and C ++ respectively.
My question is:
- I missed something, or we can really check for double or floating, as with current Java and C ++.
- If possible, can we do this in an earlier version of Java and C ++?
Conclusion (based on all the tips):We
should not use "float == float or double == double" to check if two floats or two doubles are equal (if we want to get the right answer), the
reasons are in all the answers and comments
below .
Edition (first time):Thank you so much for your help!But a minute ago I’ll just try them under Java (1.7), everyone shows
yes ,
it seems we
can really do this in current Java!
float x = 0.0f; if (x == 0) System.out.println("yes"); else System.out.println("no"); float y = 100.0f - 50.0f*2.0f + 45.0f*3 - 135.0f; if (y == 0.0f) System.out.println("yes"); else System.out.println("no"); if (100.0f - 50.0f*2.0f + 45.0f*3 - 135.0f == 0.0f) System.out.println("yes"); else System.out.println("no");
Edition (second time):But I tried this, Java also shows
yes , (in Java (1.7)).
I try to
exclude the "pre-compute" compiler and break the calculation into several steps.
float a = 100.0f; float b = 50.0f; float c = 2.0f; float bc = b * c; System.out.println("b*c = " + bc); float d = 45.0f; float e = 3.0f; float de = d * e; System.out.println("d*e = " + de); float f = 135.0f; float g = a - bc + de - f; float h = 0.0f; if (g == h) System.out.println("yes"); else System.out.println("no");
Edition (third time):
Thanks for @DiegoBasch
counterexample (for float == float):
This time Java (1.7) shows "
no ".
float m = 0.37f - 0.36f; float n = 0.01f; if (m - n == 0.0f) System.out.println("yes"); else System.out.println("no");
source share