0

Assuming that my computer use IEEE 754 floating-point encoding, I wonder what is the smallest number for which the following function return false:

constexpr bool test(const unsigned long long int x)
{
    return static_cast<unsigned long long int>(static_cast<double>(x)) == x;
}
Vincent
  • 57,703
  • 61
  • 205
  • 388

1 Answers1

1

The mantissa on a double in IEEE-754 is 53 bits (52 bits and one hidden, being very technical). That means that if the highest bits in x are above bit 52, and some of the lower bits are non-zero, the compare will fail.

You could find this out by writing a piece of code:

unsigned long long x = 0x1;

while(x > 0)
{
   x <<= 1ULL;
   if (!test(x+1))
   {
      cout << "x=" << hex << x << endl;
      break;

   }
}

Edit: fixed up code a little bit after actually testing it.

It does print x=20000000000000 as predicted.

Or, if you want to use <limits>, you can achieve the same result with:

numeric_limits<double> n;
cout << "digits=" << dec << n.digits << " -> " << hex << (1ULL << n.digits) << endl;
Mats Petersson
  • 126,704
  • 14
  • 140
  • 227
  • Is it possible to compute this number at compile-time using std::numeric_limits ? – Vincent Apr 23 '13 at 14:46
  • Probably. Let me get back to you after I've experimented a little bit - I don't know off the top of my head exactly which one of the fields does that, but I think it can be done. – Mats Petersson Apr 23 '13 at 14:48