srand() working

Why does this generate the same random number each time ??

As far as I understand srand(time(0)) tells the random number generator rand() to start with a new number each time it is executed.

If this is the case, then here each time we must have a new time(0) value as it is system time in seconds. Thus we must have different numbers but why it is generating the same ones.



1
2
3
4
5
  for(int i = 0; i<225; i++)
    {
        srand(time(0));
		printf(" %d ", rand());
    }
srand() is used once at the start of the program.

Due to the speed of the processor, time(0) is likely to return the same value if used successively in a small loop (such as here).
Do you know how roulette wheel looks like? It is a circle that has numbers. The numbers are not in simple sequential (1, 2, 3, ...) order, but somehow suffled.

Imagine that rand() has a big wheel and it remembers current position. Every time you call rand(), you get the value from the position and the position increments by one.

If you start reading from same position, you will always get the same serie of "random" numbers.


What does the srand() do? It changes the current position.
Which starting position do you pick? time(0), current time.


What is the resolution of the clock? How much time has to pass, before time(0) returns a different (next) value?

How many instructions -- how many iterations of the loop -- can the CPU process before we see change in time? Before the srand() sets different starting position for rand()?

If time(0) is in seconds, then a whole second has to pass before time changes. CPU's have clock in GHz range. GHz means 1'000'000'000 cycles per one second.


That said, the use (and learning) of rand() and srand() is no longer recommended. The produce very "low quality" randomness. C++ has in its library the <random> that has better alternatives.
For example, see http://www.cplusplus.com/reference/random/uniform_int_distribution/
If it was something like 1e9 then we would have diff value right
Generally speaking, the pseudo-random number generator should only be seeded once, before any calls to rand(), and the start of the program. It should not be repeatedly seeded, or reseeded every time you wish to generate a new batch of pseudo-random numbers.

https://en.cppreference.com/w/c/numeric/random/srand
an on the other side, you want to reseed it to reset the sequence if you want to run the same random test cases repeatedly or some other idea where repeating the values is useful. There are a number of places where this can be useful, but making random values is not one of them.

Thanks, everyone! I just want to know why is it happening and implemented Internally and I got the answer
Hello kollim,

This video is worth watching:

https://channel9.msdn.com/Events/GoingNative/2013/rand-Considered-Harmful

Andy
Topic archived. No new replies allowed.