Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does std::uniform_real_distribution<double> produce NaN? [duplicate]

Tags:

c++

random

c++11

I've got a line:

std::uniform_real_distribution<T> distribution(std::numeric_limits<T>::lowest(), 
                                               std::numeric_limits<T>::max());

It compiles but crashes on Debug(VS 2017CE). My guess is that, according to documentation of std::uniform_real_distribution:

Requires that a ≤ b and b-a ≤ std::numeric_limits<RealType>::max()

when my b is ::max() and a is ::lowest(), condition:

b-a ≤ std::numeric_limits<RealType>::max()

is not fulfilled as b-a basically doubles the value of max. Is there any work around for this so that I will keep such a wide numbers range? ::min() works perfectly but omits negative values. Problem occurs for floating numbers only.

like image 921
PStarczewski Avatar asked Nov 18 '22 01:11

PStarczewski


1 Answers

One simple solution, at least for the common IEEE-754 floating point numbers, would be randomly flipping the sign of a random non-negative number:

std::uniform_real_distribution<T> distribution(0., 
                                               std::numeric_limits<T>::max());
auto rn = distribution(eng);
return someRandomFlag ? rn : -rn;

where someRandomFlag is chosen uniformly from {true, false}.

like image 92
Baum mit Augen Avatar answered Feb 24 '23 18:02

Baum mit Augen