Why does a float variable stop incrementing at 16777216 in C#?

后端 未结 4 1138
南笙
南笙 2020-12-03 00:18
float a = 0;
while (true)
{
    a++;
    if (a > 16777216)
        break; // Will never break... a stops at 16777216
}

Can anyone explain this t

4条回答
  •  旧时难觅i
    2020-12-03 01:01

    Imagine this in decimal form. Suppose you had the number:

    1.000000 * 10^6
    

    or 1,000,000. If all you had were six digits of accuracy, adding 0.5 to this number would yield

    1.0000005 * 10^6
    

    However, current thinking with fp rounding modes is to use "Round to Even," rather than "Round to Nearest." In this instance, every time you increment this value, it will round back down in the floating point unit back to 16,777,216, or 2^24. Singles in IEE 754 is represented as:

    +/- exponent (1.) fraction
    

    where the "1." is implied and the fraction is another 23 bits, all zeros, in this case. The extra binary 1 will spill into the guard digit, carry down to the rounding step, and be deleted each time, no matter how many times you increment it. The ulp or unit in the last place will always be zero. The last successful increment is from:

    +2^23 * (+1.) 11111111111111111111111 -> +2^24 * (1.) 00000000000000000000000
    

提交回复
热议问题