4

I have a problem with the addition of two float numbers. Code below:

float a = 30000.0f;
float b = 4499722832.0f;

printf("%f\n", a+b);

Why the output result is 450002816.000000? (The correct one should be 450002832.)

mskfisher
  • 3,291
  • 4
  • 35
  • 48
Hengfeng Li
  • 381
  • 1
  • 5
  • 12

3 Answers3

7

Float are not represented exactly in C - see http://en.wikipedia.org/wiki/Floating_point#IEEE_754:_floating_point_in_modern_computers and http://en.wikipedia.org/wiki/Single_precision, so calculations with float can only give an approximate result.

This is especially apparent for larger values, since the possible difference can be represented as a percentage of the value. In case of adding/subtracting two values, you get the worse precision of both (and of the result).

Ofir
  • 8,194
  • 2
  • 29
  • 44
  • 3
    It doesn't really have anything to do with C per se - floating point numbers in general can't exactly represent every number within their range. It's inherent to the whole idea of floating point numbers. – caf Sep 07 '11 at 13:25
3

Floating-point values cannot represent all integer values.

Remember that single-precision floating-point numbers only have 24 (or 23, depending on how you count) bits of precision (i.e. significant figures). So as values get larger, you begin to lose low-end precision, which is why the result of your calculation isn't quite "correct".

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
2

From wikipedia

Single precision, called "float" in the C language family, and "real" or "real*4" in Fortran. This is a binary format that occupies 32 bits (4 bytes) and its significand has a precision of 24 bits (about 7 decimal digits).

So your number doesn't actually fit in float. You can use double instead.

Shahbaz
  • 46,337
  • 19
  • 116
  • 182
  • Right - note that in this case, the answer *is* correct to 7 decimal places. – caf Sep 07 '11 at 13:25
  • In fact, you should pretty much never use `float` unless for some reason memory is _really_ tight. Use `double` unless you have a strong reason not to. – Daniel Sep 07 '11 at 13:30
  • Or if you know your values don't get too high or too low. Like I myself always use `float`s in writing graphics code. – Shahbaz Sep 07 '11 at 13:51