Re: Comparing floating point values in Java



Philipp wrote:
I'm aware of problems (rounding, NaN etc) when comparing floating point values in computers.

In Java, will unchanged values compare strictly true if equal?
Is it _guaranteed_ that the following code does output "true" on all JVMs?

Thanks for answers. Phil

example code:
public class Test {
public static void main(String[] args) {
float a = 1;
float b = 1;
System.out.println("a == b?: " + (a == b));
}
}

I would suggest that
any JVM where it would output false
is probably non-compliant.

Your example may be somewhat lacking
as many scalar values
and many fractions where the denominator is a cardinal exponent of 2
correspond exactly
to a floating point representation.

Personally I like to think of floating point values
as representing bounded infinite sets of real values
(or not bounded - for positive and negative infinity).


There are some that take a dim view on the liberties Sun / Gosling took in the way Java deals with IEEE754 values, eg.;
<http://www.cs.berkeley.edu/~wkahan/JAVAhurt.pdf>
.



Relevant Pages

  • Re: weird problem
    ... I already told you that the comparison between an integer and a float ... And now a question about something else: why do you use floating ... use then to copy a float into a char *1. ... binary representation doesn't resemble a string like "123.46343" ...
    (comp.lang.c)
  • Re: float vs. double?
    ... There have been repeated myths that float is faster than double. ... In antique machines, the ... Note that the floating-point ALU of Intel chips supports an 80-bit floating point number, ... is different precision being stored? ...
    (microsoft.public.vc.mfc)
  • Re: Rounding of the double
    ... I still think you can do what you want using DWORDs and just assume the decimal position rather than using floats of doubles. ... I think you're going to have the same problem in any language as the floating point technology is not specific to C++ or unmanaged C++. ... /* Round a double or float to 'sig' places to the left or right of the decimal. ... As Joe says "there is no accurate representation of 0.80 in IEEE floating ...
    (microsoft.public.vc.mfc)
  • Re: converting float to double
    ... necessarily the one preferred for financial transactions. ... What he has is a float that approximates the desired value. ... I'd say eschew floating point except where necessary ... cents = lrint ...
    (comp.lang.c)
  • Re: 0.0 versus 0.0f
    ... a 64-bit floating point value. ... I am not sure what DOUBLE vs. float has to do with what I said. ... so an external floating-point math coprocessor ... And the language does define what happens, but how is the language supposed ...
    (microsoft.public.vc.mfc)