From 8c26b8516fa39238cf474703ec6313a02ffd5cfe Mon Sep 17 00:00:00 2001 From: Artem Sharipov Date: Sun, 23 Mar 2025 23:22:27 +0500 Subject: [PATCH] Fix failed build with compile flag: -Werror=float-equal (#741) --- src/unity.c | 6 ++++-- src/unity_internals.h | 15 +++++++++++++-- 2 files changed, 17 insertions(+), 4 deletions(-) diff --git a/src/unity.c b/src/unity.c index 7fa2dc63..f330e398 100644 --- a/src/unity.c +++ b/src/unity.c @@ -337,10 +337,12 @@ void UnityPrintFloat(const UNITY_DOUBLE input_number) static const int sig_digits = 9; static const UNITY_INT32 min_scaled = 100000000; static const UNITY_INT32 max_scaled = 1000000000; + static const UNITY_DOUBLE epsilon = UNITY_DOUBLE_PRECISION; #else static const int sig_digits = 7; static const UNITY_INT32 min_scaled = 1000000; static const UNITY_INT32 max_scaled = 10000000; + static const UNITY_DOUBLE epsilon = UNITY_FLOAT_PRECISION; #endif UNITY_DOUBLE number = input_number; @@ -353,7 +355,7 @@ void UnityPrintFloat(const UNITY_DOUBLE input_number) } /* handle zero, NaN, and +/- infinity */ - if (number == 0.0f) + if (UNITY_ABS(number) < epsilon) { UnityPrint("0"); } @@ -420,7 +422,7 @@ void UnityPrintFloat(const UNITY_DOUBLE input_number) #ifndef UNITY_ROUND_TIES_AWAY_FROM_ZERO /* round to even if exactly between two integers */ - if ((n & 1) && (((UNITY_DOUBLE)n - number) == 0.5f)) + if ((n & 1) && (UNITY_ABS((UNITY_DOUBLE)n - number - 0.5f) < epsilon)) n--; #endif diff --git a/src/unity_internals.h b/src/unity_internals.h index 562f5b6d..702ef078 100644 --- a/src/unity_internals.h +++ b/src/unity_internals.h @@ -259,8 +259,14 @@ typedef UNITY_FLOAT_TYPE UNITY_FLOAT; #ifndef UNITY_IS_NAN #ifndef isnan /* NaN is the only floating point value that does NOT equal itself. - * Therefore if n != n, then it is NaN. */ -#define UNITY_IS_NAN(n) ((n != n) ? 1 : 0) + * Therefore if n != n, then it is NaN. + * + * Another way to define NaN is to check whether the number belongs + * simultaneously to the set of negative and positive numbers, including 0. + * Therefore if ((n >= 0) == (n < 0)), then it is NaN. + * This implementation will not cause an error with the compilation flag: + * -Werror=float-equal */ +#define UNITY_IS_NAN(n) ((((n) >= 0.0f) == ((n) < 0.0f)) ? 1 : 0) #else #define UNITY_IS_NAN(n) isnan(n) #endif @@ -276,6 +282,11 @@ typedef UNITY_FLOAT_TYPE UNITY_FLOAT; #endif #endif +/* Calculates the absolute value of the given number */ +#ifndef UNITY_ABS + #define UNITY_ABS(n) (((n) < 0) ? -(n) : (n)) +#endif + #endif /*-------------------------------------------------------