1

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.

Ami Tavory
  • 74,578
  • 11
  • 141
  • 185
dhaval nagar
  • 111
  • 11
  • Search for the glibc code to know how is it actually implemented and the rand maual page on how rand and srand interact. – Harald Jan 24 '16 at 10:33

3 Answers3

2

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. "

Prabindh
  • 3,356
  • 2
  • 23
  • 25
  • i visited the page u given above , and seen this :int myrand(void) { next = next * 1103515245 + 12345; return((unsigned)(next/65536) % 32768); }, void mysrand(unsigned seed) { next = seed; } is this the formula used for generating random numbers. – dhaval nagar Jan 24 '16 at 10:32
1

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;
}
Humam Helfawi
  • 19,566
  • 15
  • 85
  • 160
1

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:

  1. If you initialize srand with a given seed, the following rand calls will be consistent across runs.

  2. If you initialize srand with a time-based seed, the following rand calls will almost surely be different across runs.

  3. 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.

Community
  • 1
  • 1
Ami Tavory
  • 74,578
  • 11
  • 141
  • 185