Pseudo-random number generators
This is in response to a recent request for a random number
generator. The following contains only 5 lines of code, and
has the advantage that the reference carefully describes why
it is a "good" generator. There is also a test to verify that
the implementation is correct. The test is also included.
/*--------------------------------------------------------------------*/
/*----- Park, S.K., and Miller, K.W., "Random Number Generators: -----*/
/*----- Good Ones Are Hard to Find," Communications of the ACM, -----*/
/*----- Oct., 1988, pp 1192-1201. -----*/
/*--------------------------------------------------------------------*/
int random (int old) {
/*--------------------------------------------------------------------*/
/*----- There is a simple test to verify that the implementation -----*/
/*----- is correct. See below. -----*/
/*--------------------------------------------------------------------*/
static int a = 16807, m = 2147483647, q = 127773, r = 2836;
int new;
new = a*(old % q) - r*(old / q);
if (new > 0) return new;
else return (new + m);
Quote:
}
/*--------------------------------------------------------------------*/
/*----- Test to verify the implementation -----*/
/*--------------------------------------------------------------------*/
/*
int main () {
int k, num;
num = 1;
for (k=1; k <= 10005; k++) {
num = Rand(num);
if (k > 9995) {
put_commas(k, 8); <-- Use printf instead of this
put_commas(num, 15); <-- local function.
putchar('\n');
}
}
Quote:
}
k random number
-------+---------------
9,996 721,631,166 <-- printf will work, but put_commas
9,997 1,614,852,353 <-- makes much nicer results.
9,998 925,166,085
9,999 1,484,786,315
10,000 1,043,618,065 <-- Test is to get this value!!!!!
10,001 1,589,873,406
10,002 2,010,798,668
10,003 543,060,237
10,004 407,903,509
10,005 866,474,539
*/
/*--------------------------------------------------------------------*/
Dan Stubbs