Farbod Ahmadian
Farbod Ahmadian

Reputation: 747

C++ Deeper look inside rand() and srand()

I know how rand() and srand() are related to each other, and I know how should I use them, but their mechanism of working was really interesting for me and I wanted to know How they really work?!, but I couldn't find any special thing.

So this is my question: What is going on in deep inside of rand() and srand() and how does it produce a random number? (If it's really producing a random one!) Does it have any special mathematics calculation or any special algorithm? what is it?

Upvotes: 0

Views: 285

Answers (1)

warchantua
warchantua

Reputation: 1213

First of all, rand() does not produce random numbers. It is a Pseudo Random Number Generator.

rand() is typically implemented as linear congruential generator. You can think that there is a variable seed, which holds previous state of generator, then rand() just uses this seed to generate next number in a sequence.

Something like this (very rough implementation, just to explain the idea):

const int RAND_MAX = 32767; // usually it is 2^15, but actually implementation specific
const int a = ...;          // implementation specific
const int c = ...;          // implementation specific
int seed = 0;               // current generator state

void srand(int _seed) {
  seed = _seed;
}

int rand() {
  int r = (a * seed + c) % RAND_MAX;
  seed = r;
  return r;
}

It will create the same sequence for the same initial state (seed value).

Upvotes: 4

Related Questions