Reputation: 111
I want to know what is the formula used for generating random numbers using the rand()
function in C++. At first I though it would return random numbers every time, but it does not.
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
cout << "Hello world!" << endl;
srand(9865);
cout << rand() << "\n";
return 0;
}
Here I thought that, maybe because of given seed number and that unknown formula, it will be showing same number.
But, when i removed "srand(9865);" and execute several times it is showing only "41" as output. Please explain me what is all going on here.
Upvotes: 1
Views: 2020
Reputation: 76297
The library specifications don't dictate the formula for the random number generator (it is up to the implementation). The only things specified are that things can be controlled via srand
for consistent pseudo-random generation:
In order to generate random-like numbers, srand is usually initialized to some distinctive runtime value, like the value returned by function time (declared in header <ctime>). This is distinctive enough for most trivial randomization needs.
So:
If you initialize srand
with a given seed, the following rand
calls will be consistent across runs.
If you initialize srand
with a time-based seed, the following rand
calls will almost surely be different across runs.
If you do not initialize srand
, the following calls to rand
will use the default initial seed.
Note that in contemporary C++, you should avoid using these ancient functions. See the answers to this question.
Upvotes: 1
Reputation: 3504
From http://linux.die.net/man/3/rand
"If no seed value is provided, the rand() function is automatically seeded with a value of 1. ", and "..These sequences are repeatable by calling srand() with the same seed value. "
Upvotes: 2
Reputation: 20264
You have to seed your random function with a non static seed every time. One simple but not so accurate solution is to seed it with the clock:
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
cout << "Hello world!" << endl;
srand(time(NULL));
cout << rand() << "\n";
return 0;
}
Upvotes: 1