Search code examples
c++unsigned-long-long-int

Strange unsigned long long int behavior


I was using unsigned long long int for some calculations but

std::cout << std::setprecision(30) << 900000000000001i64+4*pow(10, 16);

Gives Output:40900000000000000

and this

std::cout << std::setprecision(30) << 900000000000011i64+4*pow(10, 16);

Gives Output:40900000000000008

Now i have no idea what is happening i tried removing i64 tries printing 4*pow(10, 16) gives the correct result 40000000000000000 also tried printing 40900000000000011 directly, it prints the correct result. It works fine for power of 10^14 but after that it starts to behave strangely.

Can someone explain what is happening?


Solution

  • The reason you get this awkward result is because of loosing the values of the least significant bits in double type. double mantissa can only hold about 15 decimal digits and exactly 52 binary digits (wiki).

    900000000000001i64+4*pow(10, 16) will be converted to double trimming all lower bits. In you case there are 3 of them.

    Example:

    std::cout << std::setprecision(30);
    std::cout << 900000000000001i64 + 4 * pow(10, 16) << endl;
    std::cout << 900000000000002i64 + 4 * pow(10, 16) << endl;
    std::cout << 900000000000003i64 + 4 * pow(10, 16) << endl;
    std::cout << 900000000000004i64 + 4 * pow(10, 16) << endl;
    std::cout << 900000000000005i64 + 4 * pow(10, 16) << endl;
    std::cout << 900000000000006i64 + 4 * pow(10, 16) << endl;
    std::cout << 900000000000007i64 + 4 * pow(10, 16) << endl;
    std::cout << 900000000000008i64 + 4 * pow(10, 16) << endl;
    std::cout << 900000000000009i64 + 4 * pow(10, 16) << endl;
    

    will produce result:

    40900000000000000
    40900000000000000
    40900000000000000
    40900000000000000
    40900000000000008
    40900000000000008
    40900000000000008
    40900000000000008
    40900000000000008
    40090000000000008
    

    Notice how the values are rounded to 23.