Add a macro for checking approximate values

A macro like this is useful to avoid direct comparisons between floating
point values.

https://gitlab.gnome.org/GNOME/glib/issues/914
This commit is contained in:
Emmanuele Bassi 2017-02-08 17:34:23 +00:00
parent 61ccf733cc
commit 24e98e38d6
3 changed files with 24 additions and 0 deletions

View File

@ -219,6 +219,7 @@ MAX
<SUBSECTION>
ABS
CLAMP
G_APPROX_VALUE
<SUBSECTION>
G_STRUCT_MEMBER

View File

@ -1788,6 +1788,26 @@
* Returns: the value of @x clamped to the range between @low and @high
*/
/**
* G_APPROX_VALUE:
* @a: a numeric value
* @b: a numeric value
* @epsilon: a numeric value that expresses the tolerance between @a and @b
*
* Evaluates to a truth value if the absolute difference between @a and @b is
* smaller than @epsilon, and to a false value otherwise.
*
* For example,
* - `G_APPROX_VALUE (5, 6, 2)` evaluates to true
* - `G_APPROX_VALUE (3.14, 3.15, 0.001)` evaluates to false
* - `G_APPROX_VALUE (n, 0.f, FLT_EPSILON)` evaluates to true if `n` is within
* the single precision floating point epsilon from zero
*
* Returns: %TRUE if the two values are within the desired range
*
* Since: 2.58
*/
/**
* G_STRUCT_MEMBER:
* @member_type: the type of the struct field

View File

@ -329,6 +329,9 @@
#undef CLAMP
#define CLAMP(x, low, high) (((x) > (high)) ? (high) : (((x) < (low)) ? (low) : (x)))
#define G_APPROX_VALUE(a, b, epsilon) \
(((a) > (b) ? (a) - (b) : (b) - (a)) < (epsilon))
/* Count the number of elements in an array. The array must be defined
* as such; using this with a dynamically allocated array will give
* incorrect results.