Floating point confusion

int main()
{
  float x=3.4e2;
  printf("%f",x);
  return 0;
}

Output:

340.000000 // It ok.

But if you record x=3.1234e2, then there will be a way out 312.339996, and if x=3.12345678e2, there will be a way out 312.345673.

Why such a weekend? I think that if I write x=3.1234e2, there should be output 312.340000, but the actual output 312.339996using the GCC compiler.

+3
source share
2 answers

Not all fractional numbers have an exact binary equivalent, so they are rounded to the nearest value.

Simplified example

if you have 3 bits for a fraction, you can:

0
0.125
0.25
0.375
...

0.5 has an accurate representation, but 0.1 will be shown as 0.125.

, .

+9

, . , base-10, , , . .

, a float 32 , , . , 8 .

, , , . printf, , .

, ; . (, , ).

, , . Google ( , IEEE) , .

+2

Source: https://habr.com/ru/post/1767537/


All Articles