same number is displayed for a single output but the output is as expected when there is more than 1 output [duplicate]
This is a small program:
#include <iostream>
#include <cstdlib>
using namespace std;
int main() {
long x = rand();
cout << x << endl;
}
It always displays 41
.But if i modify the program like ,
#include <iostream>
#include <cstdlib>
using namespace std;
int main() {
for( int i = 0 ; i <= 9 ; i++ ) {
long x = rand();
cout << x << endl;
}
}
The output is as expected.The set of random numbers. OUTPUT:
41
18467
6334
26500
19169
15724
11478
29358
26962
24464
But why i get the same number when i run first program How does rand
actually function ?
The random number generator built in compilers are usually pseudo random number generator. They typically use a recursive equation to generate next random number and use a seed to generate first random number. Check this link.
To avoid having same random number as the first one, you need to change the seed. Again, same seed will give you same initial random number as well as same random number sequence. So you should change the seed every time you run your program/thread.
To set the seed, you need to call srand(). The best way to change the seed value every time srand()
is called is to use current timestamp: time(0)
.
You need to seed the random number generator with srand
.
This is often done with:
srand(time(0));
if having a different series every second is enough.
The time
function just returns the current time in seconds since the epoch 1970-01-01 00:00:00 +0000 (UTC).
From: http://www.gnu.org/s/hello/manual/libc/ISO-Random.html
Function: void srand (unsigned int seed)
This function establishes seed as the seed for a new series of pseudo-random numbers. If you call rand before a seed has been established with srand, it uses the value 1 as a default seed.
If you provide the same seed in srand
, you will always get the same sequence of numbers. If you never call srand
, then you will always get the same sequence every time you run your application.
A common trick to seed rand
is to used time(0)
- basically read the system's clock. This is fine in a simple application that just needs to be "mostly random".
But, when true randomness really is important:
Beware that you shouldn't simply seed from the system time in an application that must be cryptographically secure (e.g. something doing authentication hash calculations), or have a strong guarantee of randomness (e.g. a gambling game for real money).
In fact, you shouldn't use rand
at all in such an application. Instead, you should use a different random function; possibly one that is OS specific (specially provided for cryptography), or use a true physical source of random numbers.
精彩评论