Reputation: 7408
all
I am afraid that I have to bother you with a frequently asked question. Fortunately, my problem seems a little different from the ones you are familiar with.
Here is my code:
vector<double> rand_array;
rand_array.resize(length);
srand(time(NULL));
for(int i = 0; i < length; i++)
{
double d = rand() % 100;
d = d/double(100);
rand_array[i] =d;
}
The codes above do generate a serie of random number between 0 and 1. However, when I run these codes few times (e.g. 100 times), I found that there are some of serie has totally same elements, especially the adjacent series.
May I know why is this? And how can I generate series of random number that really random?
Many thanks in advance, and appologies again for this simple question.
Regards
Long
Upvotes: 0
Views: 136
Reputation: 47620
All generated numbers depends only on number you pass to srand
. You pass time there, so if you run it two times in one second you'll get the same sequence.
If you need to run that in program just don't call srand
multiple times. If you need to be different on different runs of program you may try to make seed more random. For example on unix-like system you may try reading /dev/random/
for seed
Upvotes: 0
Reputation: 110108
You should only run srand(time(NULL));
once in your program, at the beginning of main()
.
On most systems, time(NULL)
returns a time in seconds. This means that if you run srand(time(NULL))
twice in the same second, you will get the same random seed and as a result the same random sequence. For this reason you should not call it more than once.
Upvotes: 3