Commit 108bc1f4 authored by Jean-Baptiste Mouret's avatar Jean-Baptiste Mouret
Browse files

clean the random generation API

parent 4cb240ae
......@@ -18,10 +18,11 @@ namespace limbo {
template <typename StateFunction, typename AggregatorFunction, typename Opt>
void operator()(const StateFunction& seval, const AggregatorFunction&, Opt& opt) const
{
auto rgen = tools::make_rgen(0.0, 1.0);
for (int i = 0; i < Params::init_randomsampling::samples(); i++) {
Eigen::VectorXd new_sample(StateFunction::dim_in);
for (size_t j = 0; j < StateFunction::dim_in; j++)
new_sample[j] = tools::rand<double>(0, 1);
new_sample[j] = tools::rand_double(rgen);
opt.add_new_sample(new_sample, seval(new_sample));
}
}
......
......@@ -45,72 +45,24 @@
#include <random>
#include <utility>
// someday we will have a real thread-safe random number generator...
namespace limbo {
namespace tools {
// NOT Thread-safe !
template <typename T>
inline T rand(T max = 1.0)
{
assert(max > 0);
static std::mt19937 twister(std::time(0));
static std::uniform_real_distribution<double> distr(0.0, max);
return distr(twister);
}
template <typename T>
inline T rand(T min, T max)
{
assert(max != min);
assert(max > min);
T res = T(rand<double>() * ((long int)max - (long int)min) + min);
assert(res >= min);
assert(res < max);
return res;
}
template <typename T>
inline T gaussian_rand(T m = 0.0, T v = 1.0)
{
double facteur = sqrt(-2.0f * log(rand<double>()));
double trigo = 2.0f * M_PI * rand<double>();
return T(m + v * facteur * cos(trigo));
}
inline void rand_ind(std::vector<size_t>& a1, size_t size)
{
a1.resize(size);
for (size_t i = 0; i < a1.size(); ++i)
a1[i] = i;
for (size_t i = 0; i < a1.size(); ++i) {
size_t k = rand(i, a1.size());
assert(k < a1.size());
std::swap(a1[i], a1[k]);
}
}
/// return a random it in the list
template <typename T>
inline typename std::list<T>::iterator rand_in_list(std::list<T>& l)
// usage :
// auto rgen = make_rgen();
// double r = rand_double(rgen);
using rand_gen_t = std::mt19937;
using uniform_dist_t = std::uniform_real_distribution<double>;
using rdist_t = std::pair<rand_gen_t, uniform_dist_t>;
inline rdist_t make_rgen(double min, double max)
{
int n = rand(l.size());
typename std::list<T>::iterator it = l.begin();
for (int i = 0; i < n; ++i)
++it;
return it;
std::random_device rd;
return std::make_pair(std::mt19937(rd()), std::uniform_real_distribution<double>(min, max));
}
inline bool flip_coin() { return rand<double>() < 0.5f; }
template <typename L>
inline typename L::iterator rand_l(L& l)
inline double rand_double(rdist_t& rgen)
{
size_t k = rand(l.size());
typename L::iterator it = l.begin();
for (size_t i = 0; i < k; ++i)
++it;
return it;
rand_gen_t& gen = std::get<0>(rgen);
uniform_dist_t& dist = std::get<1>(rgen);
return dist(gen);
}
// get sign of number
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment