7

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?

Michael Petrotta
  • 59,888
  • 27
  • 145
  • 179
csguy11
  • 5,007
  • 6
  • 22
  • 20

3 Answers3

5

The wikipedia article on the subject explains a simple algorithm. There are others available, although some are patented.

Randolpho
  • 55,384
  • 17
  • 145
  • 179
5

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);
  }
}
Thilo
  • 257,207
  • 101
  • 511
  • 656
3

It depends on your libc. Most implementations (like glibc on Linux) use a linear congruential generator, though.

Here is an example:

return (int)((next = next * 1103515245 + 12345) % ((u_long)RAND_MAX + 1));

If you want higher quality random numbers, you should have a look at better algorithm's like the Mersenne Twister, which should be implemented in Boost for C++ users.

ChrisM
  • 1,114
  • 1
  • 7
  • 18