Pergunta

When we need a random number we use srand once to initialize the seed and after that we can use rand. Why do we need to seed using srand? For example srand(time(Null)); Can't we just use rand() % 99999? Am I missing something in the concept of these functions?

Foi útil?

Solução

Here's the thing,

You actually don't need to seed your random number generator. Go ahead, try it without!

BUT, you will always get the same sequence of 'random' numbers.

Pseudo-random number generators such as rand() only generate random-looking sequences. If you just start them from the 'beginning' every time, they will of course look the same.

Seeding the generator is a good way to get numbers that actually appear 'properly' random. If you seed with the time, you are starting somewhere 'random' in the sequence. Note that picking time values close together usually gives two sequences that are also very different.

You can seed with whatever you like. For example, if you have lots of threads using lots of generators, the time is a bad idea because the time may well be the same for multiple threads.

There is no clear 'good' value for the seed, so it is usually not seeded by default. This can also be a good thing if you want to 're-run' a randomised algorithm with exactly the same input: just set the seed to be the same seed.

Outras dicas

srand(0) will always return the same deterministic sequence of values, although those values will appear random.

Knowing your seed will allow an attacker to determine every number you generate.

By setting a seed, you effectively create a different sequence.

srand(0) may be entirely acceptable to your needs, if you only need the appearence of random.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top