Random number generator

Just for curiosity, how does the rand() function work? I mean, could somewone here make a new rand() function using reverse engineering?
Thanks in advance.
Something like this:

1
2
3
4
#define RAND_MAX 32767          /* (2^15 - 1) */

SEED = (1103515245*SEED + 12345) % (pow(2,15));
X = SEED;


Although theoretically, it could be whatever you wanted, as long as it generates number within 0-RAND_MAX.
Yes, but in this case your rand function will always return a fixed value, not a random number.
http://en.wikipedia.org/wiki/Linear_congruential_generator

The part that adds the variation to rand() is calling srand(time(0)). rand() is completely deterministic.

EDIT: By the way, firedraco, I really hope you code your powers of 2 as 1<<n, rather than pow(2,n).
Last edited on
Hi,
I would suggest using an extensively tested open-source random number generator library. One example: http://www.boost.org/doc/libs/1_41_0/libs/random/index.html
Skip the mod altogether and let the size of the variable/register do the modulo inherently.
Topic archived. No new replies allowed.