0

When adding a large number to a large result obtained by power function in c++, the final answer is somehow getting incremented or decremented by 1.

#include "bits/stdc++.h"
using namespace std;
#define dbg(x) cout<<#x<<" = "<<x<<ln

unsigned long long bla = pow(10, 16-1) + 8999999999999997;
dbg(bla);
unsigned long long blb = pow(10, 16-1) + 8111111111111111;
dbg(blb);

The output for the above code is:

bla = 9999999999999996
blb = 9111111111111112

You can see that the result has swayed by 1 in each case.

However this problem disappears and I get the correct result when I split the operation into 2 lines as shown in the code below:

unsigned long long bla = pow(10, 16-1);
bla += 8999999999999997;
dbg(bla);

I believe this phenomenon is caused because the numbers are approaching the 64 bit length which is causing some issues in addition but I would greatly appreciate some clarity about why this is actually happening.

  • 2
    To explain why it is a dup: `pow` returns a `double`, so the line `pow(10, 16-1) + 8999999999999997` is calculated with `double` values, not `unsigned long long`. – mch Aug 20 '21 at 08:25
  • [Losing precision with floating point numbers (double) in c++](https://stackoverflow.com/q/48148235/995714), [Precision loss with double C++](https://stackoverflow.com/q/12096852/995714), [Why IEEE754 single-precision float has only 7 digit precision?](https://stackoverflow.com/q/19130396/995714) – phuclv Aug 20 '21 at 08:26

0 Answers0