samedi 21 janvier 2017

How to generate uniformly distributed random reals for custom types without reinventing the wheel?

I was going to use std::uniform_real_distribution with some non-builtin floating-point-like types, e.g. half_float::half or boost::multiprecision::float128. But what I get is

/opt/gcc-5.2/include/c++/5.2.0/bits/random.h:1868:7: error: static assertion failed: template argument not a floating point type

from g++ 5.2. Here's the example program (compile with g++ -std=c++11 -fext-numeric-literals test.cpp -o test):

#include <random>
#include <boost/multiprecision/float128.hpp>
#include <half.hpp>

template<typename Float>
void test()
{
    std::random_device rd;
    std::mt19937 mt(rd());
    std::uniform_real_distribution<Float> rnd(Float(1),Float(10));
}

int main()
{
    test<float>();
    test<double>();
    test<long double>();
    test<boost::multiprecision::float128>(); // doesn't compile
    test<half_float::half>(); // doesn't compile
}

So, how is one supposed to generate uniformly distributed random reals for such custom types? Is there a way to go without reinventing the wheel?




Aucun commentaire:

Enregistrer un commentaire