Re: Comparing floating point values in Java




Philipp wrote:
Hello,
I'm aware of problems (rounding, NaN etc) when comparing floating point
values in computers.
In C++ this goes a bit further as you cannot compare with certitude
floating point numbers even if you have made exactly the same operations
on each of them (see eg:
http://www.parashift.com/c++-faq-lite/newbie.html#faq-29.18 )

My question: 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));
}
}

Look into StrictMath.

It might also be worthwhile to learn how to calculate error, and
compare signifigant figures only. If you only need a "probably equal",
then you can use a delta, eg:

public class FloatEquality {
public static boolean areEqual(float a, float b, float delta) {
return Math.abs(a - b) < delta;
}
public static float DELTA_F = 0.00000001f;
public static void main(String[] args) {
float a = 1f;
float b = 1f;
System.out.println("a == b?: " + areEqual(a, b, DELTA_F);
}
}

Hope this helps.

Daniel.

.



Relevant Pages

  • Re: pointer and array
    ... impossible to compare the values, ... int 3 and the float 3.14, that are equal when we convert them both ... the "double" 33554433.0 becomes 33554432.0 after conversion to ...
    (comp.lang.c)
  • Re: compare two float values
    ... float t, check; ... Don't compare for equality, won't work for float, rather compare ... compatible implementation, exactly one of these three will be true ... operations are usually not exact, and two calculations that you think ...
    (comp.lang.c)
  • Re: Comparing floating point values in Java
    ... In Java, will unchanged values compare strictly true if equal? ... float a = 1; ... I was calculating an array of float values from some user input. ...
    (comp.lang.java.programmer)
  • Re: compare two float values
    ... float t, check; ... Don't compare for equality, won't work for float, rather compare ... exact equality of the two entities. ... differ if their calcualtion and assignment were not ...
    (comp.lang.c)
  • Comparing floating point values in Java
    ... when comparing floating point values in computers. ... will unchanged values compare strictly true if equal? ... float a = 1; ...
    (comp.lang.java.programmer)