Why does the addition of two float numbers is incorrect in C?

10,250

Solution 1

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).

Solution 2

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".

Solution 3

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.

Share:
10,250
Hengfeng Li
Author by

Hengfeng Li

A passionate coder.

Updated on June 09, 2022

Comments

  • Hengfeng Li
    Hengfeng Li over 1 year

    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.)