Search code examples
c++cgccdouble

GCC C/C++ double behavior


Possible Duplicate:
C++ double precision and rounding off

Code:

int main(void)
{
    double a = 12;
    double b = 0.5;
    double c = 0.1;

    std::cout.precision(25);
    std::cout << a << std::endl;
    std::cout << b << std::endl;
    std::cout << c << std::endl;
    std::cout << a + b << std::endl;
    std::cout << a + c << std::endl;

    return 0;
}

Output:

12
0.5
0.1000000000000000055511151
12.5
12.09999999999999964472863

Why does GCC represent 0.1 and 0.5 differently? When adding, they are represented differently. It seems 0.5 and whole numbers a represented differently that other floats. Or is this just something going on in the io library? What causes this behavior?


Solution

  • Just as decimal numbers with a finite number of digits can only exactly represent numbers that are a sum of powers of 10, binary floating point numbers can only exactly represent numbers that are a sum of powers of 2.

    In this case, 0.1 cannot be represented as a finite sum of powers of 2, whereas 0.5 and 12 can (0.5 is equal to 2-1 and 12 is equal to 23 + 22).

    As a further example, 0.75 can also be exactly represented in binary floating point, because it can be expressed as 2-1 + 2-2.