Couple of days back I wrote a piece of code which was behaving in an unexpected manner. I was confused what was happening. Take a look at the sample code below and predict its behavior
package com.shekhar; public class JavaPuzzler { public static void main(String[] args) { JavaPuzzler javaPuzzler = new JavaPuzzler(); javaPuzzler.doSth(); } public void doSth() { float f = 1.2f; if (f >= 1.0) { f = 0.9999999999999f; } InnerClass innerClass = new InnerClass(f); System.out.println(innerClass.getValue()); } private class InnerClass { private float value; public InnerClass(float value) { if (value >= 1.0f) { throw new IllegalArgumentException( "Value can't be greater than 1.0f"); } this.value = value; } public float getValue() { return value; } } }
My initial expectation was that I would get value 0.9999999999999f as answer.Try it and find the answer. Share your answer and reasoning in comments.
Hello Shekhar,
to show, what has to be shown, this code would be enough:
public class JavaPuzzler {
public static void main(String[] args) {
System.out.println(0.9999999999999f == 1.0);
}
}
This behaviour is a result of the binary representation of floats: The fact that the value range of float in Java is from ±1,4E−45 to ±3,4E+38 does not mean, that there are really distinct float values for every possible value in this range. And the difference betwean two adjacent float values is different in different areas of the range of float. In your example 0.9999999999999f and 1.0 are mapped to the same float value.
Greetings,
Michael
It is because of the inaccuracy of binary representation of float.. This link should explain it further http://mindprod.com/jgloss/floatingpoint.html
Same reason why Java gives 0.89999999… for System.out.println(2.0 – 1.1); Try running the same in groovy as well.
Always nice to alert people for this, but I agree with Michael that you could have trimmed the code a little.
I was initially looking for some weird interaction between inner classes, but that was totally irrelevant.
not a puzzler at all, perfectly normal for a computer
Nothing new about this. And the example was very boring to read. i loved Michael Paap’s Example. When i saw this link I thought it was some new bug. But Shucks..
Not a puzzler really. You can go through this link to know more about why these calculations are made the way they are -> http://floating-point-gui.de/basic/
Whatever you do, do not make such calculations (using float / double) on programs that involve transactions involving real money or something equally critical.
Anyway, you are wiser now.
Too old problem to show…