Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random doubles are always infinite

Tags:

c++

random

c++11

I have the following:

    std::random_device rd;
    std::mt19937_64 randEng(rd());
    std::uniform_real_distribution<double> rg(std::numeric_limits<double>::lowest(), std::numeric_limits<double>::max());

    for(size_t i = 0; i < numToGenerate; i++){
        nums[i] = rg(randEng);
        std::cout << nums[i] << std::endl;
    }   

Where nums is a vector presized to numToGenerate

Every number that is printed out though says inf my understanding was that I had set this up to get random numbers between in this case -1.79769e+308 and 1.79769e+308 as it happens to be on my machine. What am I doing wrong here in the set up of this random number generator

like image 598
csteifel Avatar asked Mar 19 '23 03:03

csteifel


1 Answers

Probably the computation of the pseudorandom number includes the difference (max-min). For example to compute a random number between A and B a simple approach would be:

x = A + rnd*(B - A)

where rnd is a random number between 0 and 1. If you do this with the maximum and minimum double precision value you get a problem, because that difference is bigger than the maximum and thus will become "infinite".

After that A + rnd*infinite is always infinite if rnd is not zero, and NaN when it's zero.

like image 186
6502 Avatar answered Mar 20 '23 18:03

6502