From 5aaf09018f6664620e5b9e987a65429b799a9cd8 Mon Sep 17 00:00:00 2001 From: Jean-Baptiste Perrier Date: Wed, 18 Aug 2021 12:49:53 +0200 Subject: [PATCH] Add missing NearEqual for double --- Source/Engine/Core/Math/Mathd.h | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/Source/Engine/Core/Math/Mathd.h b/Source/Engine/Core/Math/Mathd.h index 47b16b608..8f7ac05b7 100644 --- a/Source/Engine/Core/Math/Mathd.h +++ b/Source/Engine/Core/Math/Mathd.h @@ -248,6 +248,34 @@ namespace Math return ulp > maxUlp; } + /// + /// Checks if a and b are almost equals, taking into account the magnitude of double precision floating point numbers + /// + /// The left value to compare + /// The right value to compare + /// True if a almost equal to b, otherwise false + static bool NearEqual(double a, double b) + { + // Check if the numbers are really close - needed when comparing numbers near zero + if (IsZero(a - b)) + return true; + + // Original from Bruce Dawson: http://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/ + const int64 aInt = *(int64*)&a; + const int64 bInt = *(int64*)&b; + + // Different signs means they do not match + if (aInt < 0 != bInt < 0) + return false; + + // Find the difference in ULPs + const int64 ulp = Abs(aInt - bInt); + + // Choose of maxUlp = 4 + // according to http://code.google.com/p/googletest/source/browse/trunk/include/gtest/internal/gtest-internal.h + const int maxUlp = 4; + return ulp <= maxUlp; + } /// /// Checks if a and b are almost equals within the given epsilon value.