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
#include <cstdlib>
#include <ctime>
#include <iostream>
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
2
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?
The most fundamental problem of your test application is that you call
srandonce and then callrandone time and exit.The whole point of
srandfunction is to initialize the sequence of pseudo-random numbers with a random seed.It means that if you pass the same value to
srandin two different applications (with the samesrand/randimplementation) then you will get exactly the same sequence ofrand()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 secprecision. 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 Martin York already mentioned in a comment to the question).
Actually you should call
srand(seed)one time and then callrand()many times and analyze that sequence – it should look random.AMENDMENT 1 – example code:
OK I get it.
Apparently verbal description is not enough (maybe language barrier or something… 🙂 ).
Old-fashioned C code example based on the same
srand()/rand()/time()functions that was used in the question:^^^ THAT sequence from a single run of the program is supposed to look random.
Please NOTE that I don’t recommend to use
rand/srandfunctions in production code for the reasons explained below and I absolutely don’t recommend to use functiontimeas 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.
^^^ THAT kind of intuitive 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.
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). For example if you combine two high quality PRNGs by using them both in turns – you may produce bad resulting sequence – despite them generating good sequences each separately (those two good sequences may simply correlate to each other and thus combine badly).
Specifically
rand()/srand(s)pair of functions provide a singular per-process non-thread-safe(!) pseudo-random number sequence generated with implementation-defined algorithm. Functionrand()produces values in range[0, RAND_MAX].Quote from C11 standard (ISO/IEC 9899:2011):
Many people reasonably expect that
rand()would produce a sequence of semi-independent uniformly distributed numbers in range0toRAND_MAX. Well it most certainly should (otherwise it’s useless) but unfortunately not only standard doesn’t require that – there is even explicit disclaimer that states "there is no guarantees as to the quality of the random sequence produced".In some historical cases
rand/srandimplementation was of very bad quality indeed. Even though in modern implementations it is most likely good enough – but the trust is broken and not easy to recover.Besides its non-thread-safe nature makes its safe usage in multi-threaded applications tricky and limited (still possible – you may just use them from one dedicated thread).
New class template std::mersenne_twister_engine<> (and its convenience typedefs –
std::mt19937/std::mt19937_64with good template parameters combination) provides per-object pseudo-random number generator defined in C++11 standard. With the same template parameters and the same initialization parameters different objects will generate exactly the same per-object output sequence on any computer in any application built with C++11 compliant standard library. The advantage of this class is its predictably high quality output sequence and full consistency across implementations.Also there are other (much simpler) PRNG engines defined in C++11 standard – std::linear_congruential_engine<> (historically used as fair quality
srand/randalgorithm in some C standard library implementations) and std::subtract_with_carry_engine<>. They also generate fully defined parameter-dependent per-object output sequences.Modern day C++11 example replacement for the obsolete C code above:
The version of previous code that uses std::uniform_int_distribution<>