user3234111
user3234111

Reputation: 31

Floating point arithmetic and comparing of floating point values

For these lines of code, I get back 0 as an output that is they are all equal to each other. Now if I understand correctly, a b and c may store slightly different versions of the true value .3 hence when do a Float.compare(...) against these values, I expect to get back as an output a value other than 0. Why do I get them as 0?

float a = 0.15f + 0.15f;
float b = 0.1f + 0.2f;
float c = 0.3f;
System.out.println(Float.compare(a,  b));  //<--- outputs 0
System.out.println(Float.compare(a,  c));  //<--- outputs 0
System.out.println(Float.compare(b,  c));  //<--- outputs 0

Upvotes: 2

Views: 153

Answers (1)

Erwin Bolwidt
Erwin Bolwidt

Reputation: 31299

Because, as you say, they may store slightly different versions. But with these simple expressions, there is no loss of precision, so a, b and c all contain exactly the same version of .3f.

For fun, try this. Here you will lose precision, and the result of the comparison will not be 0:

public static void main(String[] args) {
    float a = .3f;
    float b = .3f;
    a = (float) Math.cos(a);
    a = (float) Math.acos(a);
    System.out.println(Float.compare(a, b));
}

Upvotes: 1

Related Questions