jeudi 13 août 2020

Seeding independent bits engine with boosts multiprecision

I have a simple rejection sampling application which is wrapped in a class and used externally as the dummy example below shows. I was able to adapt this post to a boost::multiprecision use case. However I'm not sure how to appropriately seed the generator and can't find any random_device equivalent for boost.

The below code 'works', but if you run it multiple times in quick succession you will get the same random numbers which I don't want. Is there something more sensitive than time(NULL)?

#include <iostream>
#include <boost/multiprecision/cpp_dec_float.hpp>
#include <boost/multiprecision/cpp_int.hpp>
#include <boost/random.hpp>

using namespace boost::multiprecision; // used only for SO post
using namespace boost::random;

typedef independent_bits_engine<boost::mt19937, std::numeric_limits<cpp_dec_float_50>::digits, cpp_int> generator;


generator &gen()
{
  thread_local static generator genny(time(NULL));
  return genny;  
}

class dummy {
    public:
        dummy() = default;
        cpp_dec_float_50 rejectionSample() {
           uniform_real_distribution<cpp_dec_float_50> ur(0,1);
           cpp_dec_float_50 x = ur(gen());
           while (x > 0.1) 
               x = ur(gen());
           return x;
        }
};



int main()
{
    std::cout << std::setprecision(std::numeric_limits<cpp_dec_float_50>::digits10) << std::showpoint;

    dummy d;
    int nToGet = 5;
    for (int i = 0; i < nToGet; ++i) 
        std::cout << d.rejectionSample() << std::endl;
}



Aucun commentaire:

Enregistrer un commentaire