csteifel
csteifel

Reputation: 2934

Random doubles are always infinite

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

Upvotes: 4

Views: 165

Answers (1)

6502
6502

Reputation: 114579

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.

Upvotes: 7

Related Questions