In C:
float a = 1.3;
if (a == 1.3)
printf("Hello c");
else
printf("Bye c");
//output: Bye c
In Java:
float a = 1.3;
if (a == 1.3)
System.out.println("Hello java");
else
System.out.println("Bye java");
//output: Hello java
Why is this so?
You cannot exactly represent "1.3" as a binary float.
The conversion of the literal 1.3 to a float will result in a floating point number that is close to but not exactly equal to 1.3.
In the Java case you struck lucky because the JVM interprets the "1.3" as a standard java float and converts to the same almost 1.3. binary number. In the C case the standard says 1.3 should be interpreted as a "double" and converts it to a binary floating point that is a little closer to the decimal value 1.3 than the ordinary float.
The bottom line is that you should never compare floats for equality as small variations in storage, order of calculation etc. will produce slightly different results. You should always "bracket" any float comparison like so:
if (a > 1.299 && a < 1.301) // something close to 1.3
Just to help you wrap your brain around the answer, let me give you a simple analogy. Remember that floating point numbers are approximate. Many numbers cannot be exactly represented. Now, imagine we do the same thing with decimals, say we use six digits after the decimal place.
How do we represent 1/3? .333333
is the best we can do. But now 3 * 1/3
will not equal 1.
How do we represent 2/3? .666666
will at least ensure 2 * 1/3 = 2/3
. But 2/3 + 1/3
will not equal 1.
We can represent 2/3 as .666667
. But then 2 * 1/3
won't equal 2/3
. But at least 1/3 + 2/3
will equal one.
So the point is, with approximate representations, you can't ensure exactly right answers, only close enough answers. In general, you should never compare floating point numbers for equality unless you are 100% positive you understand what you are doing and why.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With