Search code examples
c++doublelong-long

How to compare a long long with a double?


(This has to be a duplicate, but I can't find a duplicate...)
How do I properly compare a long long with a double in C++?

Casting either to the other can cause loss of precision and possibly overflow, so I'm not sure what to do...


Solution

  • Honestly: Use a long double on a platform where long doubles have a 64-bit significand.

    If you want to handle platforms without such support:

    I'm going to assume a long long is 64-bit and a double is the usual IEEE 64-bit double.

    If d >= 0x1.0p63, then your long long is less than it. If d < -0x1.0p63, then your long long is greater than it. If d != d, the comparison should return false because d is NaN. If fabs(d) >= 0x1.0p53, d represents an integer, so you can convert d to long long and do your comparison with long longs. Otherwise, you can convert ll to double and do your comparison with doubles; if any low bits are lost, they are irrelevant to the comparison.

    Code (uncompiled and untested):

    #define COMPAR(a, b) ((a) < (b) ? -1 : (a) == (b) ? 0 : 1)
    int compar(long long a, double b) {
      if (b != b) return false;
      if (b >= 0x1.0p63) return -1;
      if (b < -0x1.0p63) return 1;
      if (fabs(b) >= 0x1.0p53) return COMPAR(a, (long long)b);
      else return COMPAR((double)a, b);
    }
    #undef COMPAR