1

aのサイズが4バイトの場合、おそらく間違って計算したので、そこからまたはその周辺のどこかに数字floatを保持できるはずではありません。8,388,607-8,388,608

(0.1)の値がまだ右の間にあるのに、なぜf余分を表示するのですか?15f8,388,607-8,388,608

int main(int argc, const char * argv[])
{
    @autoreleasepool {
        float f = .1;
        printf("%lu", sizeof(float));
        printf("%.10f", f);
    }
    return 0;
}

2012-08-28 20:53:38.537 prog[841:403] 4
2012-08-28 20:53:38.539 prog[841:403] 0.1000000015
4

1 に答える 1

2

The values -8,388,608 ... 8,388,607 lead me to believe that you think floats use two's complement, which they don't. In any case, the range you have indicates 24 bits, not the 32 that you'd get from four bytes.

Floats in C use IEEE754 representation, which basically has three parts:

  • the sign.
  • the exponent (sort of a scale).
  • the fraction (actual digits of the number).

You basically get a certain amount of precision (such as 7 decimal digits) and the exponent dictates whether you use those for a number like 0.000000001234567 or 123456700000.

The reason you get those extra digits at the end of your 0.1 is because that number cannot be represented exactly in IEEE754. See this answer for a treatise explaining why that is the case.

Numbers are only representable exactly if they can be built by adding inverse powers of two (like 1/2, 1/16, 1/65536 and so on) within the number of bits of precision (ie, number of bits in the fraction), subject to scaling.

So, for example, a number like 0.5 is okay since it's 1/2. Similarly 0.8125 is okay since that can be built from 1/2, 1/4 and 1/16.

There is no way (at least within 23 bits of precision) that you can build 0.1 from inverse powers of two, so it gives you the nearest match.

于 2012-08-29T01:12:17.823 に答える