From 4a15111a6867e38b8381e3d6a24ad0604feb7c9a Mon Sep 17 00:00:00 2001 From: Ivo Hedtke Date: Wed, 24 Mar 2021 13:23:15 +0100 Subject: [PATCH] Avoid asking for a discrete_distribution when all weights are zero --- include/dkm.hpp | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/include/dkm.hpp b/include/dkm.hpp index 38d1b68..b5c50dd 100644 --- a/include/dkm.hpp +++ b/include/dkm.hpp @@ -87,6 +87,13 @@ std::vector> random_plusplus(const std::vector // Calculate the distance to the closest mean for each data point auto distances = details::closest_distance(means, data); // Pick a random point weighted by the distance from existing means + // If all distances are 0, the normalization step in std::discrete_distribution can cause a floating point + // exception, thus we check that: + double distance_sum = std::accumulate(distances.begin(), distances.end(), 0.0); + if (FP_ZERO == std::fpclassify(distance_sum)) { + // all distances zero, thus we want just a distribution with equal probability for everything + std::fill(distances.begin(), distances.end(), 1.0); + } // TODO: This might convert floating point weights to ints, distorting the distribution for small weights #if !defined(_MSC_VER) || _MSC_VER >= 1900 std::discrete_distribution generator(distances.begin(), distances.end());