float a = 0; while (true) { a++; if (a > 16777216) break; // Will never break... a stops at 16777216 }
Can anyone explain this to me why a float value stops incrementing at 16777216 in this code?
Edit:
Or even more simple:
float a = 16777217; // a becomes 16777216
Floating-point decimal values generally do not have an exact binary representation due to how the CPU represents floating point data. For this reason, you may experience a loss of precision, and some floating-point operations may produce unexpected results.
Scalars of type float are stored using four bytes (32-bits). The format used follows the IEEE-754 standard. The mantissa represents the actual binary digits of the floating-point number.
A float variable can contain whole numbers and fractions Float is a shortened term for "floating point." By definition, it's a fundamental data type built into the compiler that's used to define numeric values with floating decimal points. C, C++, C# and many other programming languages recognize float as a data type.
To initialize a variable with float value, use assign operator and assign the floating point value to the variable. Variable name has to be on the left hand side and the float value has to be on the right side. In the following Python program, we have initialized variables x and y with float values.
Short roundup of IEEE-754 floating point numbers (32-bit) off the top of my head:
(sign ? -1 : +1) * 2^exponent * (1.0 + mantissa)
1001 0000 0000 0000 0000 000 = 2^-1 + 2^-4 = .5 + .0625 = .5625
and the value in front of the decimal separator is not stored but implicitly assumed as 1 (if exponent is 255, 0 is assumed but that's not important here), so for an exponent of 30, for instance, this mantissa example represents the value 1.5625
Now to your example:
16777216 is exactly 224, and would be represented as 32-bit float like so:
10010111
)0 10010111 00000000000000000000000
(+1) * 2^24 * (1.0 + .0) = 2^24 = 16777216
Now let's look at the number 16777217, or exactly 224+1:
(+1) * 2^24 * (1.0 + 2^-24) = 2^24 + 1 = 16777217
16777217 cannot be represented exactly with a float. The next highest number that a float can represent exactly is 16777218.
So, you try to increment the float value 16777216 to 16777217, which cannot be represented in a float.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With