Skip to content

Commit df803c8

Browse files
Fix failed build with compile flag: -Werror=float-equal (#741)
1 parent cdf1d02 commit df803c8

File tree

2 files changed

+17
-4
lines changed

2 files changed

+17
-4
lines changed

Diff for: src/unity.c

+4-2
Original file line numberDiff line numberDiff line change
@@ -337,10 +337,12 @@ void UnityPrintFloat(const UNITY_DOUBLE input_number)
337337
static const int sig_digits = 9;
338338
static const UNITY_INT32 min_scaled = 100000000;
339339
static const UNITY_INT32 max_scaled = 1000000000;
340+
static const UNITY_DOUBLE epsilon = UNITY_DOUBLE_PRECISION;
340341
#else
341342
static const int sig_digits = 7;
342343
static const UNITY_INT32 min_scaled = 1000000;
343344
static const UNITY_INT32 max_scaled = 10000000;
345+
static const UNITY_DOUBLE epsilon = UNITY_FLOAT_PRECISION;
344346
#endif
345347

346348
UNITY_DOUBLE number = input_number;
@@ -353,7 +355,7 @@ void UnityPrintFloat(const UNITY_DOUBLE input_number)
353355
}
354356

355357
/* handle zero, NaN, and +/- infinity */
356-
if (number == 0.0f)
358+
if (UNITY_ABS(number) < epsilon)
357359
{
358360
UnityPrint("0");
359361
}
@@ -420,7 +422,7 @@ void UnityPrintFloat(const UNITY_DOUBLE input_number)
420422

421423
#ifndef UNITY_ROUND_TIES_AWAY_FROM_ZERO
422424
/* round to even if exactly between two integers */
423-
if ((n & 1) && (((UNITY_DOUBLE)n - number) == 0.5f))
425+
if ((n & 1) && (UNITY_ABS((UNITY_DOUBLE)n - number - 0.5f) < epsilon))
424426
n--;
425427
#endif
426428

Diff for: src/unity_internals.h

+13-2
Original file line numberDiff line numberDiff line change
@@ -259,8 +259,14 @@ typedef UNITY_FLOAT_TYPE UNITY_FLOAT;
259259
#ifndef UNITY_IS_NAN
260260
#ifndef isnan
261261
/* NaN is the only floating point value that does NOT equal itself.
262-
* Therefore if n != n, then it is NaN. */
263-
#define UNITY_IS_NAN(n) ((n != n) ? 1 : 0)
262+
* Therefore if n != n, then it is NaN.
263+
*
264+
* Another way to define NaN is to check whether the number belongs
265+
* simultaneously to the set of negative and positive numbers, including 0.
266+
* Therefore if ((n >= 0) == (n < 0)), then it is NaN.
267+
* This implementation will not cause an error with the compilation flag:
268+
* -Werror=float-equal */
269+
#define UNITY_IS_NAN(n) ((((n) >= 0.0f) == ((n) < 0.0f)) ? 1 : 0)
264270
#else
265271
#define UNITY_IS_NAN(n) isnan(n)
266272
#endif
@@ -276,6 +282,11 @@ typedef UNITY_FLOAT_TYPE UNITY_FLOAT;
276282
#endif
277283
#endif
278284

285+
/* Calculates the absolute value of the given number */
286+
#ifndef UNITY_ABS
287+
#define UNITY_ABS(n) (((n) < 0) ? -(n) : (n))
288+
#endif
289+
279290
#endif
280291

281292
/*-------------------------------------------------------

0 commit comments

Comments
 (0)