Random Numbers
John Woods
john at frog.UUCP
Tue Sep 10 06:17:31 AEST 1985
>
> What is the best way to generate random numbers in C.
> The application in question is to extract a random line of a file.
>
> (I realize that this has been done in programs such as 'fortune')
> --
>
Glad you asked. Knuth's The Art of Computer Programming, Volume 2, Section
3 "Random Numbers" is a good place to start. I doubt that there is a One
Best Way, but for your amusement and entertainment, I supply my own C
implementation of Algorithm A (Additive number generator). Knuth likes this
algorithm, but says "there is still very little theory to prove that it does
or does not have desirable randomness properties", but that in practice, it
has appeared to work.
---------slice,-dice,-chop,-grate,-and-cut-here---------------------------
/*
* Knuth's 55-number random number generator
* Algorithm A (Additive number generator)
* p27, S 3.2.2, Volume 2 of The Art of Computer Progamming
*/
/* 24 and 55 are not just Random Numbers, but are Sacred Numbers of the
* algorithm, hence I have not #defined them, lest a nonbeliever be led astray
*/
static int RANDU[55] = { /* a name of power */
/* insert 55 of your own favorite random numbers here, not all
even. Due to varying "int" lengths, I am not providing any.
Calling the traditional rand() 55 times is probably sufficient.
*/
};
static int *X24 = &RANDU[23], *X55 = &RANDU[54];
rand() {
int rv;
rv = *X55 = (*X55 + *X24--);
if (X24 < &RANDU[0]) X24 = &RANDU[54];
if (--X55 < &RANDU[0]) X55 = &RANDU[54];
return rv;
}
srand(n) {
*X55 = n;
}
--
John Woods, Charles River Data Systems, Framingham MA, (617) 626-1101
...!decvax!frog!john, ...!mit-eddie!jfw, jfw%mit-ccc at MIT-XX.ARPA
"Out of my way, I'm a scientist!"
- War of the Worlds
More information about the Comp.lang.c
mailing list