# Why are floats converted from different integers sometimes equal?

I'm trying to understand the following algorithm:

int ubnd = Integer.MAX_VALUE
int lbnd = ubnd
lbnd = lbnd - 1
}
lbnd = lbnd + 1
print "$lbnd..$ubnd"


I don't see why for 63 iterations of the loop, we have (float)lbnd == (float)ubnd. It has something to do with the conversion of integers to floats, but I don't know what. I know that integers and floats both have 32 bits, but there must be a different way of storing them. Could someone help me out?

• Start by understanding why, when ubnd=MAX_VALUE and lbnd=MAX_VALUE-1, we have (float)lbnd == (float)ubnd. Try to figure out how those two numbers will be represented in floating point after conversion to floating point -- try writing down the bit representation. What will the mantissa be for each? How many bits are reserved for the mantissa, in Java's float? I suggest working through those details on your own, then editing the question if you still can't solve it to show what progress you've made, or answering your own question if that does enable you to solve it yourself. – D.W. Sep 18 '18 at 1:11
• @gnasher729 It does depend on what exactly "float" means. I'm assuming IEEE floats, which are language-independent. Since we've had questions about number formats before, I'm inclined to leave the question be here. I removed the references to Java, though; please adapt your answer to make reasonable language-independent assumptions on the number formats. – Raphael Sep 18 '18 at 9:32
• Please use Markdown formatting instead of images in the future, and pseudo-code instead of real code. If your question relies on real code, your question is very likely offtopic here and should be on Stack Overflow. – Raphael Sep 18 '18 at 9:33

"float" and "int" in Java both use 32 bits. "float" can represent some numbers that "int" can't, like 0.5. Since 32 bits let you store exactly $2^{32}$ different values, it should be obvious that there must be "int" values that you cannot store in a "float".
"float" in Java, and "float" in many other language implementations, uses one bit for the sign, 8 bits for an exponent, and 23 bits plus one implicit bit for the mantissa. As numbers get bigger, the distance from one "float" to the next gets bigger. The 23 bit mantissa lets you store exactly the integers in the range $2^{23}≤x<2^{24}$, all the even integers in the range $2^{24}≤x<2^{25}$, all multiples of four in the range $2^{25}≤x<2^{26}$ etc.