1

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?

Sarthak Singh
  • 193
  • 3
  • 12

2 Answers2

7

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.

Ivan Gritsenko
  • 4,166
  • 2
  • 20
  • 34
0

Please try this code (notice the explicit type conversion there).

typedef unsigned long long ULONG64; //Not a must, but just for code clarity

std::cout << std::setprecision(30) << 900000000000001i64 + (ULONG64)(4 * pow(10, 16));
//output -> 40900000000000001
std::cout << std::setprecision(30) << 900000000000011i64 + (ULONG64)(4 * pow(10, 16));
//output -> 40900000000000011

You have to tell compiler to do explicit type conversion (to ULONG64) on result returned by pow(...) function which is of type double.

A.B.
  • 1,554
  • 1
  • 14
  • 21