I'm using this to get a properly rounded integer division:
Math.round((float)dividend/(float)divisor)
Division by 0 is already handled elsewhere. Other than that, could this ever fail?
I could imagine the result of that division being a float that should be something.5
, but actually evaluates to something.4999997
or so. Does such a float exist?
To check this myself, I tried to print out all floats that are close to .5 like this:
for(int i=Integer.MIN_VALUE+1; i!=Integer.MIN_VALUE; i++){
float f=Float.intBitsToFloat(i);
if ((f>(int)f+0.4999999 && f<(int)f+0.5000001 && f!=(int)f+0.5)
||(f<(int)f-0.4999999 && f>(int)f-0.5000001 && f!=(int)f-0.5)){
System.out.println(Float.toString(f));
}
}
(Integer.MIN_VALUE
was checked manually.)
That only printed:
-0.4999999
-0.49999994
-0.49999997
-0.50000006
0.4999999
0.49999994
0.49999997
0.50000006
Since -0.5
and 0.5
are definitely floats, that would mean that no such float exists. But maybe there's a possibility that my range is too small and a problematic numbers goes outside of it. I wanted a second opinion anyway, so I'm asking here, maybe someone has advanced inside knowledge about IEEE754 and has proof why this absolutely cannot ever happen.
Broadening the range by one digit had this result, none of those numbers answer this question.
Related question: What about something.99999
? A similar test had this result. All those floats are distinct from the floats for their exact integers.