Re: What is the behaviour of double / float primitive == comparison?
Endre Stølsvik <[email protected]>
| Newsgroups | gmane.comp.windows.devel.java.advanced |
|---|---|
| Message-ID | <[email protected]> |
Carfield Yim wrote:
> I am not really clear about the definition of JLS:
>
>
> Otherwise, two distinct floating-point values are considered unequal
> by the equality operators. In particular, there is one value
> representing positive infinity and one value representing negative
> infinity; each compares equal only to itself, and each compares
> unequal to all other values.
>
> http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#5198
>
>
> Say for following case, will this print true?
>
> System.out.println( 3.0/7.0 == 1.5/3.5 )
public static void main(String[] args) {
float a = .1f / .3f;
float b = .3f / .9f;
System.out.println(a);
System.out.println(Long.toBinaryString(Float.floatToRawIntBits(a)));
System.out.println(b);
System.out.println(Long.toBinaryString(Float.floatToRawIntBits(b)));
System.out.println(a == b);
}
Prints out:
0.3333333
111110101010101010101010101010
0.33333334
111110101010101010101010101011
false
With your numbers, it becomes
0.42857143
111110110110110110110110110111
0.42857143
111110110110110110110110110111
true
The == comparison will return true if the actual bits are the same. This
will depend on how the calculations pan out: how will the numbers you're
going to divide be represented in binary, and how will the result of the
division between these two numbers be represented?
Btw, half values happen to be perfect for binary to represent, since
decimal .5 is "0.1" in floating binary. Decimal 0.1 is, however,
impossible to represent in floating binary.
well..
Use BigDecimal. Or multiply away the fraction part and do your
calculations using integers. Exact real values (floating point!) are a
lie anyway! (Your desk isn't 2 meters across..)
PS: don't use float in any case, use double.
PPS: Even more hilarious is the effect of JIT on floating point
calculations: at the compilation point, you suddenly get the precision
of the native (math co-)processor instead of the interpreter. This might
be higher than what the IEEE standard defines (and the interpreter
gives), apparently in particular regarding the exponent. The 'strictfp'
keyword can fix this particular issue, so that you get just as bad
accuracy when it is compiled - this to ensure perfect portability across
platforms.
Kind regards,
Endre.
===================================
This list is hosted by DevelopMentor® http://www.develop.com
View archives and manage your subscription(s) at http://discuss.develop.com