I am trying to generate random doubles with a roughly equal probability for all representable finite values. I believe this would be something like a randomly signed exponential_distribution
, a uniform_distribution
won't work because the representable doubles are not uniformly distributed. I have this hacky code that seems to do what I want:
#include <cmath>
#include <iostream>
#include <random>
template < class GEN >
double double_distribution (GEN& generator)
{
using gen_type = typename GEN::result_type;
static_assert (sizeof (gen_type) == sizeof (double), "");
union {gen_type g; double f;} result;
do {
result.g = generator();
} while (!std::isfinite (result.f));
return result.f;
}
int main() {
std::mt19937_64 mt ((std::random_device())());
for (int n = 0; n < 10; ++n) {
std::cout << double_distribution (mt) << ' ';
}
std::cout << '\n';
}
but I'm wondering if there is a simpler way to approximate this using one of the STL's existing RandomNumberDistribution classes?