summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorEmmanuele Bassi <ebassi@gnome.org>2017-02-08 17:34:23 +0000
committerEmmanuele Bassi <ebassi@gnome.org>2018-05-29 09:55:47 +0100
commit24e98e38d616f64d68c86747dc38e657145bf38b (patch)
tree137198fb9e51906b8f17d6536ed5c679b84c844b
parent61ccf733ccf1f64760553f6915fc7264ca1af1d6 (diff)
downloadglib-24e98e38d616f64d68c86747dc38e657145bf38b.tar.gz
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
-rw-r--r--docs/reference/glib/glib-sections.txt1
-rw-r--r--glib/docs.c20
-rw-r--r--glib/gmacros.h3
3 files changed, 24 insertions, 0 deletions
diff --git a/docs/reference/glib/glib-sections.txt b/docs/reference/glib/glib-sections.txt
index 32a7664e8..1a5c9fa5e 100644
--- a/docs/reference/glib/glib-sections.txt
+++ b/docs/reference/glib/glib-sections.txt
@@ -219,6 +219,7 @@ MAX
<SUBSECTION>
ABS
CLAMP
+G_APPROX_VALUE
<SUBSECTION>
G_STRUCT_MEMBER
diff --git a/glib/docs.c b/glib/docs.c
index 080c1b0de..5a786311c 100644
--- a/glib/docs.c
+++ b/glib/docs.c
@@ -1789,6 +1789,26 @@
*/
/**
+ * 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
* @struct_p: a pointer to a struct
diff --git a/glib/gmacros.h b/glib/gmacros.h
index 0e180bb09..cfeb9a00b 100644
--- a/glib/gmacros.h
+++ b/glib/gmacros.h
@@ -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.