#include const long MM = 2147483647; /* luckily, this is a Mersenne prime */ const long AA = 48271; const long QQ = 44488; const long RR = 3399; long seed = 4071776L; /* This is an initial seed. Change it to anything you like to get a different sequence of pseudo-random numbers */ void set_seed(long new_seed) { seed = new_seed; } double prandom () /* A pseudorandom number generator due to Donald Knuth The Art of Computer Programming Volume 2 Semi-numerical Algorithms It uses a modulo technique to generate a fairly unpredictable and well-distributed sequence of seeds. It returns a double formed by dividing the seed by MAXINT */ { long new_seed; new_seed = AA * (seed % QQ) - RR * (seed / QQ); if (new_seed > 0) seed = new_seed; else seed = new_seed + MM; return ( (double) seed / (double) MM ); } double prandom_range (double lo, double hi) /* Scale the result so it lies between lo and hi */ { if (hi > lo) return ( lo + (hi-lo) * prandom() ); else { printf ("ERROR: in prandom.prandom_range(): lo=%lf hi=%lf\n",lo,hi); return 0; } } main(argc, argv) int argc; char *argv[]; { /* If the optional argument is on the commandline use it to reset the seed */ if (argc > 1) set_seed(atoi(argv[1])); int top = 100; /* default is ints from 0 - 99 */ if (argc > 2) top = atoi(argv[2]); /* but can be adjusted by second arg */ int i; char continu = 'g'; while (continu != 'q') { for (i = 0; i < 10; i++) { printf("%d ", (int) prandom_range(0.0,top*1.0)); } printf("\n"); printf("Hit q to quit, ENTER to continue > "); continu = getchar(); } getchar(); /* eat the CR/LF */ }