snippetcppCritical
How to generate a random number in C++?
Viewed 0 times
randomgeneratehownumber
Problem
I'm trying to make a game with dice, and I need to have random numbers in it (to simulate the sides of the die. I know how to make it between 1 and 6). Using
doesn't work very well, because when I run the program a few times, here's the output I get:
So I want a command that will generate a different random number each time, not the same one 5 times in a row. Is there a command that will do this?
#include
#include
#include
using namespace std;
int main()
{
srand((unsigned)time(0));
int i;
i = (rand()%6)+1;
cout << i << "\n";
}doesn't work very well, because when I run the program a few times, here's the output I get:
6
1
1
1
1
1
2
2
2
2
5
2So I want a command that will generate a different random number each time, not the same one 5 times in a row. Is there a command that will do this?
Solution
The most fundamental problem of your test application is that you call
The whole point of
It means that if you pass the same value to
BUT in your example application pseudo-random sequence consists only of one element - the first element of a pseudo-random sequence generated from seed equal to current time of
Obviously when you happen to run application on the same second - you use the same seed value - thus your result is the same of course (as Loki Astari already mentioned in a comment to the question).
Actually you should call
AMENDMENT 1 - example code:
Apparently verbal description is not enough for some readers (maybe language barrier or something...).
Old-fashioned C code example based on the same
^^^ THAT sequence from a single run of the program is supposed to look random.
Please NOTE that I don't recommend to use
AMENDMENT 2 - detailed explanation:
It is important to understand that as of now there is NO C or C++ standard features (library functions or classes) producing actually random data definitively (i.e. guaranteed by the standard to be actually random). The only standard feature that approaches this problem is std::random_device that unfortunately still does not provide guarantees of actual randomness.
Depending on the nature of application you should first decide if you really need truly random (unpredictable) data. Notable case when you do most certainly need true randomness is information security - e.g. generating symmetric keys, asymmetric private keys, salt values, security tokens, etc.
Actually security-grade random numbers is a separate industry worth a separate article. (I briefly touch it in this answer of mine.)
In most cases Pseudo-Random Number Generator is sufficient - e.g. for scientific simulations or games. In some cases consistently defined pseudo-random sequence is even required - e.g. in games you may generate the same map(s) each time in runtime to save installation package size.
The original question and reoccurring multitude of identical/similar questions (and even many misguided "answers" to them) indicate that first and foremost it is important to distinguish random numbers from pseudo-random numbers AND to understand what is pseudo-random number sequence in the first place AND to realize that pseudo-random number generators are NOT used the same way you could use true random number generators.
Some (totally reasonable) person would think something like this:
Intuitively when you request random number - the result returned shouldn't depend on previously returned values and shouldn't depend if
anyone requested anything before and shouldn't depend in what moment
and by what process and on what computer and from what generator and
on what planet in which galaxy it was requested. That is what word "random" means
after all - being unpredictable and independent of anything -
otherwise it is not random anymore, right?
^^^ With this intuition it is
very natural to look for some magic spells to cast to get
such random number in any possible context. BUT THAT kind of expectations IS VERY WRONG and harmful in all cases involving Pseudo-Random Number Generators - despite being reasonable for true random numbers.
While the meaningful notion of "random number" exists (kind of) - there is no such thing as "pseudo-random number". A Pseudo-Random Number Generator actually produces pseudo-random number sequence. And this Pseudo-random sequence is in fact always deterministic (predetermined by its algorithm and initial parameters) - i.e. there is actually nothing random about it.
When experts talk about quality of PRNG they actually talk about statistical properties of the generated sequence (and its notable sub-sequences). Fo
srand once and then call rand one time and exit.The whole point of
srand function is to initialize the sequence of pseudo-random numbers with a random seed.It means that if you pass the same value to
srand in two different applications (with the same srand/rand implementation) then you will get exactly the same sequence of rand() values read after that in both applications.BUT in your example application pseudo-random sequence consists only of one element - the first element of a pseudo-random sequence generated from seed equal to current time of
1 sec precision. What do you expect to see on output then?Obviously when you happen to run application on the same second - you use the same seed value - thus your result is the same of course (as Loki Astari already mentioned in a comment to the question).
Actually you should call
srand(seed) one time and then call rand() many times and analyze that sequence - it should look random.AMENDMENT 1 - example code:
Apparently verbal description is not enough for some readers (maybe language barrier or something...).
Old-fashioned C code example based on the same
srand()/rand()/time() functions that was used in the original question:#include
#include
#include
int main(void)
{
unsigned long j;
srand( (unsigned)time(NULL) );
for( j = 0; j RAND_MAX - (RAND_MAX-5)%6 )
{ /* very unlikely event that bad value retrieved
so we proceed to a next one */
}
printf( "%d,\t%d\n", n, n % 6 + 1 );
}
return 0;
}
^^^ THAT sequence from a single run of the program is supposed to look random.
Please NOTE that I don't recommend to use
rand/srand functions in production code for the reasons explained below and I absolutely don't recommend to use function time as a random seed for the reasons that IMO already should be quite obvious. Those are fine for educational purposes and to illustrate the point sometimes but for any serious use they are mostly useless.AMENDMENT 2 - detailed explanation:
It is important to understand that as of now there is NO C or C++ standard features (library functions or classes) producing actually random data definitively (i.e. guaranteed by the standard to be actually random). The only standard feature that approaches this problem is std::random_device that unfortunately still does not provide guarantees of actual randomness.
Depending on the nature of application you should first decide if you really need truly random (unpredictable) data. Notable case when you do most certainly need true randomness is information security - e.g. generating symmetric keys, asymmetric private keys, salt values, security tokens, etc.
Actually security-grade random numbers is a separate industry worth a separate article. (I briefly touch it in this answer of mine.)
In most cases Pseudo-Random Number Generator is sufficient - e.g. for scientific simulations or games. In some cases consistently defined pseudo-random sequence is even required - e.g. in games you may generate the same map(s) each time in runtime to save installation package size.
The original question and reoccurring multitude of identical/similar questions (and even many misguided "answers" to them) indicate that first and foremost it is important to distinguish random numbers from pseudo-random numbers AND to understand what is pseudo-random number sequence in the first place AND to realize that pseudo-random number generators are NOT used the same way you could use true random number generators.
Some (totally reasonable) person would think something like this:
Intuitively when you request random number - the result returned shouldn't depend on previously returned values and shouldn't depend if
anyone requested anything before and shouldn't depend in what moment
and by what process and on what computer and from what generator and
on what planet in which galaxy it was requested. That is what word "random" means
after all - being unpredictable and independent of anything -
otherwise it is not random anymore, right?
^^^ With this intuition it is
very natural to look for some magic spells to cast to get
such random number in any possible context. BUT THAT kind of expectations IS VERY WRONG and harmful in all cases involving Pseudo-Random Number Generators - despite being reasonable for true random numbers.
While the meaningful notion of "random number" exists (kind of) - there is no such thing as "pseudo-random number". A Pseudo-Random Number Generator actually produces pseudo-random number sequence. And this Pseudo-random sequence is in fact always deterministic (predetermined by its algorithm and initial parameters) - i.e. there is actually nothing random about it.
When experts talk about quality of PRNG they actually talk about statistical properties of the generated sequence (and its notable sub-sequences). Fo
Context
Stack Overflow Q#13445688, score: 163
Revisions (0)
No revisions yet.