arman - 10 months ago 53

C++ Question

I want to create a random number within the numeric limits of the

`double`

`#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`

`gcc 5.4.0`

`dist(engine)`

`inf`

`nextafter(a,0)`

`nextafter(b,0)`

`a`

`b`

`dist`

According to

`std::uniform_real_distribution`

`min`

`max`

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

The output of this is:

-1.79769e+308, 1.79769e+308

And, as expected, the following assert triggers, demonstrating the contradiction:

`const auto rand = dist(engine);`

assert(rand <= dist.max() && rand >= dist.min());

Again, same result for both compilers. As per the definitions of

`min`

`max`

Answer Source

Your code exhibits undefined behaviour, as it breaks the following condition:

N4140 § 26.5.8.2.2 [rand.dist.uni.real]

`explicit uniform_real_distribution(RealType a = 0.0, RealType b = 1.0);`

Requires:`a ≤ b`

and`b − a ≤ numeric_limits<RealType>::max()`

.