Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

srand(time(0)) and random number generation

Tags:

c++

random

srand(time(0)) 

is used in C++ to help in the generation of random numbers by seeding rand with a starting value.

But, can you explain what it exactly does?

Thanks.

like image 957
Simplicity Avatar asked Jan 19 '11 14:01

Simplicity


People also ask

What does Srand time 0 )) mean?

time(0) gives the time in seconds since the Unix epoch, which is a pretty good "unpredictable" seed (you're guaranteed your seed will be the same only once, unless you start your program multiple times within the same second).

What is difference between rand () and Srand ()?

The srand() function sets the starting point for producing a series of pseudo-random integers. If srand() is not called, the rand() seed is set as if srand(1) were called at the program start. Any other value for seed sets the generator to a different starting point.

Why do you need Srand () when getting a random number?

The generation of the pseudo-random number depends on the seed. If you don't provide a different value as seed, you'll get the same random number on every invocation(s) of your application. That's why, the srand() is used to randomize the seed itself.

How do you get a random number between 0 and 1 in C++?

C++ Random Number Between 0 And 1 We can use srand () and rand () function to generate random numbers between 0 and 1. Note that we have to cast the output of rand () function to the decimal value either float or double.


2 Answers

srand() gives the random function a new seed, a starting point (usually random numbers are calculated by taking the previous number (or the seed) and then do many operations on that number to generate the next).

time(0) gives the time in seconds since the Unix epoch, which is a pretty good "unpredictable" seed (you're guaranteed your seed will be the same only once, unless you start your program multiple times within the same second).

like image 188
orlp Avatar answered Sep 20 '22 08:09

orlp


From what I remember, there is an equation that is used to generate a sequence of values. The next value is somewhat influenced by the previous value. By using the time, you are setting the initial value of the equation. Keep in mind, the values are pseudo random.

So for example, if you do something like this:


srand(1);
srand(1);

The same sequence of numbers will be generated. However, if you do:


srand(time(0));
srand(time(0) + 1);

Two different sequences of numbers will b e generated because the seed value is different.

like image 41
user489041 Avatar answered Sep 18 '22 08:09

user489041