I’m writing a code that performs a random scan over a set of 4 numbers. I’d like to scan 10000 points (millions later). I just learned about rand(), so here’s the relevant part:
int numPoints = 10000;
double A,B,C,D;
for (i=0; i<=numPoints1;i++) {
srand ( time(NULL) );
A = rand() % 500 + 100;
B = rand() % 500 + 100;
C = rand() % 100 - 100;
D = rand() % 5 + 2.5;
Then these four variable are fed into a function (A,B,C,D).
The code performs some checks and calculations inside the loop.
}
However, I noticed in the output file that many times, the same set of A,B,C,D is picked.
Q: Any suggestions as to how can I improve the situation?
You should move the call to
srandout of the loop. Like this:What’s happening is that you’re re-initializing the random number generator with each iteration. As I recall,
timereturns the time as a number of seconds. Sotime(NULL)will only change once per second, meaning that you’ll be seeding the random number with the same seed multiple times.That said, this won’t guarantee that a set of numbers isn’t repeated. It will, however, make duplicates much less likely.