Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inside random() function - How is it implemented?

Tags:

c++

We commonly use random() function to create random numbers in C++.

The use of void srand (unsigned int seed) would improve the results since it would generate random numbers depending on the value of seed.

Can anyone tell me how the random function is actually implemented?

like image 410
csguy11 Avatar asked Sep 24 '10 02:09

csguy11


1 Answers

Here is a detailed description of the algorithm used in the GNU C library's random() function.

Basically:

#include <stdio.h>

#define MAX 1000
#define seed 1

main() {
  int r[MAX];
  int i;

  r[0] = seed;
  for (i=1; i<31; i++) {
    r[i] = (16807LL * r[i-1]) % 2147483647;
    if (r[i] < 0) {
      r[i] += 2147483647;
    }
  }
  for (i=31; i<34; i++) {
    r[i] = r[i-31];
  }
  for (i=34; i<344; i++) {
    r[i] = r[i-31] + r[i-3];
  }
  for (i=344; i<MAX; i++) {
    r[i] = r[i-31] + r[i-3];
    printf("%d\n", ((unsigned int)r[i]) >> 1);
  }
}
like image 156
Thilo Avatar answered Oct 02 '22 13:10

Thilo