From 962abebbf215337ffe4ec227d58b9e8b458f12c5 Mon Sep 17 00:00:00 2001 From: Charles Otto Date: Mon, 2 Feb 2015 18:20:23 -0800 Subject: [PATCH] Replace use of rand() in RandSample, this was resulting in poor results from RndSubspace on windows --- openbr/core/common.cpp | 15 +++++++++++++-- openbr/core/common.h | 12 +++++------- 2 files changed, 18 insertions(+), 9 deletions(-) diff --git a/openbr/core/common.cpp b/openbr/core/common.cpp index d6c445a..acc8b49 100644 --- a/openbr/core/common.cpp +++ b/openbr/core/common.cpp @@ -16,21 +16,32 @@ #include "common.h" #include +#include using namespace std; +static RandomLib::Random g_rand; +static QMutex rngLock; + /**** GLOBAL ****/ void Common::seedRNG() { - static QMutex seedControl; - QMutexLocker lock(&seedControl); + QMutexLocker lock(&rngLock); static bool seeded = false; if (!seeded) { srand(0); // We seed with 0 instead of time(NULL) to have reproducible randomness seeded = true; + g_rand.Reseed(0); } } +double Common::randN() +{ + QMutexLocker lock(&rngLock); + + return g_rand.FloatN(); +} + QList Common::RandSample(int n, int max, int min, bool unique) { QList samples; samples.reserve(n); diff --git a/openbr/core/common.h b/openbr/core/common.h index 1a9be82..843dc96 100644 --- a/openbr/core/common.h +++ b/openbr/core/common.h @@ -220,6 +220,9 @@ double KernelDensityEstimation(const V &vals, double x, double h) return y / (vals.size() * h); } +// Return a random number, uniformly distributed over 0,1 +double randN(); + /*! * \brief Returns a vector of n integers sampled in the range RandSample(int n, const QSet &values, bool unique = false); template QList RandSample(int n, const QList &weights, bool unique = false) { - static bool seeded = false; - if (!seeded) { - srand(time(NULL)); - seeded = true; - } - QList cdf = CumSum(weights); for (int i=0; i samples; samples.reserve(n); while (samples.size() < n) { - T r = (T)rand() / (T)RAND_MAX; + T r = randN(); + for (int j=0; j= cdf[j]) && (r <= cdf[j+1])) { if (!unique || !samples.contains(j)) -- libgit2 0.21.4