Skip to content

Instantly share code, notes, and snippets.

@notpeelz
Created March 7, 2015 04:42
Show Gist options
  • Save notpeelz/982ae9909b19d35f9a5f to your computer and use it in GitHub Desktop.
Save notpeelz/982ae9909b19d35f9a5f to your computer and use it in GitHub Desktop.
Floating-point number comparer
readonly Comparer<Double> doubleComparer = Comparer<Double>.Create((x, y) =>
{
long firstValue = BitConverter.DoubleToInt64Bits(x);
long secondValue = BitConverter.DoubleToInt64Bits(y);
// Compare the bit-sign
if (firstValue >> 63 != secondValue >> 63)
return firstValue == secondValue ? 0 : firstValue.CompareTo(secondValue);
long difference = Math.Abs(firstValue - secondValue);
// Is within the margin of precision loss?
return difference <= 1 ? 0 : firstValue.CompareTo(secondValue);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment