'Why does my random function generate the same number every time I call it in a loop?
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]
Solution 1:[1]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Mohammed Alaiadhy |
