Here is the code for pseudorandom.c:
/* RPJ 25viii05 -- from code by Rahul Simha */
/* Uniform [0,1] using the standard Lehmer generator.
See http://www.seas.gwu.edu/~simhaweb/java/lectures/appendix/random.html
for more details. */
#include < stdio.h>
const long m = 2147483647;
const long a = 48271;
const long q = 44488;
const long r = 3399;
long r_seed = 4071776L; /* change this to anything you like */
double prandom ()
{
long t, lo, hi;
hi = r_seed / q;
lo = r_seed - q * hi;
t = a * lo - r * hi;
if (t > 0)
r_seed = t;
else
r_seed = t + m;
return ( (double) r_seed / (double) m );
}
/* Uniform random number generator - returns a number between a and b */
double prandom_range (double a, double b)
{
if (b > a)
return ( a + (b-a) * prandom() );
else {
printf ("ERROR: in prandom.prandom_range(): a=%lf b=%lf\n",a,b); return 0;
}
}
/* generate randoms 0-99 to test */
main(argc, argv)
int argc;
char *argv[];
{
if (argc>1) r_seed = atoi(argv[1]);
do {
printf("%d\n", (int)prandom_range(0.0, 100.0));
printf("ENTER to continue, q to quit > ");
}
while(getchar() != 'q');
}
If you compile this via gcc -o pseudorandom pseuedorandom.c and run it
by simply typing pseudorandom you will get a sequence of pseudo-random
numbers in the range 0-99. It will always be exactly the same sequence
because the initial seed is fixed. By using argc and argv and
atoi() you can select a new intial seed for each run. Typing
pseudorandom 19071961 you will get a different sequence.
One last exercise. A good idea is to modify the above code.
> cards 47 ace of clubs ENTER to continue, q to quit > Joker ENTER to continue, q to quit > deuce of diamonds ENTER to continue, q to quit > ten of spades ENTER to continue, q to quit > ace of hearts ENTER to continue, q to quit > knave of spades ENTER to continue, q to quit > queen of clubs ENTER to continue, q to quit > king of hearts ENTER to continue, q to quit > 7 of diamonds ENTER to continue, q to quit > q >