Home > OS >  Why does my random function generate the same number every time I call it in a loop?
Why does my random function generate the same number every time I call it in a loop?

Time:01-26

I have my random function generating a pseudo-random number in the range:

double Utils::randomNumber(int min, int max)
{
    assert(min < max);
    srand(time(nullptr));
    return (max - min) * ((double)rand() / RAND_MAX)   min;
}

However, when I call it in a loop, I always get the very same number, although I seed the sequence:

for (int i = 0; i < m_inputs;   i)
{
    m_weights.push_back(Utils::randomNumber(0, 1));
}

Output:

Weights: [0.787561, 0.787561, 0.787561, 0.787561, 0.787561, 0.787561, 0.787561, 0.787561, 0.787561, 0.787561, 0.787561, 0.787561]

CodePudding user response:

Seeding repeatedly with tight timings will generate the same initial result after-seed every time. If seeding once per process isn't an option due to caller locality, then you should provide an initial static-state instead. What may work for you is this:

#include <random>

double Utils::randomNumber(int min, int max)
{
    static std::mt19937 rng{ std::random_device{}() };
    std::uniform_real_distribution<double> dist(min, max);
    return dist(rng);
}

Note there is an intrinsic problem on the potential ceiling of the uniform real range, and it may be applicable to your usage (not likely, but never say never). See the notes here for more information.

CodePudding user response:

I assume you are call randomNumber function from another function main or else.

if you declare the seed inside the function, you will reset the function. Resetting the function will make the same numbers appear several times, the same second.

Moving srand(time(nullptr)); to main function should solve the problem.

  •  Tags:  
  • Related