1

Why does this statement:

std::cout << 4611686018427387905 - pow(2.0, 62) << std::endl;

or:

unsigned long long int value = 4611686018427387905; //2^62 + 1
unsigned long long int result = value - pow(2.0, 62);

evaluate to 0 instead of 1? An unsigned long long int can hold up to 2^64 values so I don't think that is the issue. This also happens with other values that are very large.

user8624
  • 15
  • 3
  • 3
    Don't use `pow` for integer power operations. especially not if's 2 to the power of something. Try `unsigned long long int result = value - (1ULL << 62);` – Ted Lyngmo Dec 31 '21 at 14:31
  • 1
    Related: [Is floating point math broken?](https://stackoverflow.com/q/588004/11082165) and [Why isn't `int pow(int base, int exponent)` in the standard C++ libraries?](https://stackoverflow.com/q/2398442/11082165) – Brian61354270 Dec 31 '21 at 14:33
  • 2
    The `pow()` function returns a `double`, so your subtractions are done between 2 `double` operands ... and they have a precision of ~17 decimal digits. But your `unsigned long long` has 19 digits. – Adrian Mole Dec 31 '21 at 14:33
  • 2
    A `double` very typically has **52 bits** of unsigned precision. That's why your `2^62 + 1` isn't looking so precise. – Drew Dormann Dec 31 '21 at 14:38
  • 1
    @DrewDormann Yeah, that looks like a correct duplicate to me. – cigien Dec 31 '21 at 14:46
  • 1
    Figured it out, thank you all! – user8624 Dec 31 '21 at 15:26

0 Answers0