From 38efb29af0ebbb52a384298e47423481b7f16f36 Mon Sep 17 00:00:00 2001 From: varon Date: Sun, 19 Mar 2017 15:33:58 +0200 Subject: [PATCH] Addint based floating point approximate comparison --- src/OpenTK/Math/MathHelper.cs | 35 +++++++++++++++++++++++++++++++---- 1 file changed, 31 insertions(+), 4 deletions(-) diff --git a/src/OpenTK/Math/MathHelper.cs b/src/OpenTK/Math/MathHelper.cs index 81ad33b..a5ecc61 100644 --- a/src/OpenTK/Math/MathHelper.cs +++ b/src/OpenTK/Math/MathHelper.cs @@ -326,8 +326,35 @@ namespace OpenTK return Math.Max(Math.Min(n, max), min); } - #endregion - - #endregion - } + private static unsafe int FloatToInt32Bits(float f) { + return *((int*) &f); + } + + /// + /// Approximates floating point equality with a maximum number of different bits. + /// This is typically used in place of an epsilon comparison. + /// see: https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/ + /// see: https://stackoverflow.com/questions/3874627/floating-point-comparison-functions-for-c-sharp + /// + /// the first value to compare + /// >the second value to compare + /// the number of floating point bits to check + /// + public static bool ApproximatelyEqual(float a, float b, int maxDeltaBits) { + int aInt = FloatToInt32Bits(a); + if (aInt < 0) + aInt = Int32.MinValue - aInt; + + int bInt = FloatToInt32Bits(b); + if (bInt < 0) + bInt = Int32.MinValue - bInt; + + int intDiff = Math.Abs(aInt - bInt); + return intDiff <= (1 << maxDeltaBits); + } + + #endregion + + #endregion + } } -- 2.7.4