samedi 26 novembre 2016

What is the range limit for uniform real distributions?

I want to create a random number within the numeric limits of the double floating point range. I thought this would be easy:

#include <random>                                                                   
#include <cassert>                                                                  
#include <math.h>                                                                

int main()                                                                          
{                                                                                   
    double a = std::numeric_limits<double>::lowest();                               
    double b = std::numeric_limits<double>::max();                                  

    std::default_random_engine engine;                                           

    std::uniform_real_distribution<double> dist(a, b);                           
    assert(std::isfinite(dist(engine))); // this triggers!

    return 0;                                                                    
}                                                                                   

The assert fails for both clang 3.8.0 and gcc 5.4.0. I tried using nextafter(a,0) and nextafter(b,0) instead of a and b when constructing dist but got the same result.

According to std::uniform_real_distribution, the methods min and max should be the answer to this question, but apparently that's not the case:

std::cout << dist.min() << ", " << dist.max() << std::endl;

The output of this is:

-1.79769e+308, 1.79769e+308

Again, same result for both compilers. The assert shouldn't be triggering. What's going on?




Aucun commentaire:

Enregistrer un commentaire