commit 0b4e9a4: [Minor] Move summation to a separate routine

Vsevolod Stakhov vsevolod at highsecure.ru
Sat Mar 5 21:07:05 UTC 2022


Author: Vsevolod Stakhov
Date: 2022-03-05 20:36:40 +0000
URL: https://github.com/rspamd/rspamd/commit/0b4e9a4f0b3bfa7d3bc3a40239b41d85a15a44be

[Minor] Move summation to a separate routine

---
 src/libutil/util.c | 23 +++++++++++++++++++++++
 src/libutil/util.h |  8 ++++++++
 2 files changed, 31 insertions(+)

diff --git a/src/libutil/util.c b/src/libutil/util.c
index e7348982b..44f40280b 100644
--- a/src/libutil/util.c
+++ b/src/libutil/util.c
@@ -2456,3 +2456,26 @@ rspamd_ptr_array_shuffle (GPtrArray *ar)
 		g_ptr_array_index (ar, i) = t;
 	}
 }
+
+float
+rspamd_sum_floats (float *ar, gsize *nelts)
+{
+	float sum = 0.0f;
+	volatile float c = 0.0f; /* We don't want any optimisations around c */
+	gsize cnt = 0;
+
+	for (gsize i = 0; i < *nelts; i ++) {
+		float elt = ar[i];
+
+		if (!isnan(elt)) {
+			cnt ++;
+			float y = elt - c;
+			float t = sum + y;
+			c = (t - sum) - y;
+			sum = t;
+		}
+	}
+
+	*nelts = cnt;
+	return sum;
+}
diff --git a/src/libutil/util.h b/src/libutil/util.h
index 0eff1c990..1d53807d4 100644
--- a/src/libutil/util.h
+++ b/src/libutil/util.h
@@ -518,6 +518,14 @@ struct rspamd_controller_pbkdf {
 
 extern const struct rspamd_controller_pbkdf pbkdf_list[];
 
+/**
+ * Sum array of floats using Kahan sum algorithm
+ * @param ar
+ * @param nelts
+ * @return
+ */
+float rspamd_sum_floats (float *ar, gsize *nelts);
+
 #ifdef  __cplusplus
 }
 #endif


More information about the Commits mailing list