Created
March 7, 2015 04:42
-
-
Save notpeelz/982ae9909b19d35f9a5f to your computer and use it in GitHub Desktop.
Floating-point number comparer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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