This short article explains why we cannot use "==" to compare floats and how to compare floats right.
You can try to run this code in Java to understand the problem.
Binary representation of the number 1/3 cannot be precise, because the place where the number is stored is limited. So the number rounding was made:
So we have b = 1.0000000298023224 that is not equal to 1.0;
You can try to run this code in Java to understand the problem.
double a = 1.0f / 3.0f;
double b = a + a + a;
System.out.println(a); // Output 0.3333333432674408
System.out.println(b); // Output 1.0000000298023224
System.out.println(1 == b); // Output false
Why?
If the compared values are the results of computation, they can be not equal.Binary representation of the number 1/3 cannot be precise, because the place where the number is stored is limited. So the number rounding was made:
1/3 = 0.333.. = 0.(3) = 0.3333333432674408
So we have b = 1.0000000298023224 that is not equal to 1.0;