/* ========================================================================== unifavr.c - a simple program to compute Unif[0,1] averages. (Designed for use in conjunction with jpar.c) Copyright (c) 1999 by Jeffrey S. Rosenthal (jeff@math.toronto.edu). Licensed for general copying, distribution and modification according to the GNU General Public License (http://www.gnu.org/copyleft/gpl.html). ---------------------------------------------------- Compile with "cc unifavr.c -o unifavr". ---------------------------------------------------- USAGE: unifavr [runningtime [seed]] SYNOPSIS: unifavr will run for seconds (or 3 seconds if no runningtime is given), using the drand48() pseudo-random number generator with intial seed (or the current time in microseconds if no seed is given). During this time, it will continually average Unif[0,1] pseudo-random values. When done, it will discard any simulation in progress, and then output two quantities: the average of the pseudo-random values considered, and the number of such values averaged. ========================================================================== */ #define DEFNUMSECS 3 /* Default number of seconds to run; may be modified. */ #include #include #include main(int argc, char *argv[]) { int i, N, runningsecs, tmpseed; float tot = 0.0; double tmpval; long presenttime(); long starttime, runningtime; /* Determine running time. */ if ( (argc >= 2) && ( (runningsecs=atoi(argv[1])) > 0 ) ) ; else runningsecs = DEFNUMSECS; runningtime = runningsecs * 1000000; /* Seed the pseudo-random number generator. */ if ( (argc >= 3) && ( (tmpseed=atoi(argv[2])) > 0 ) ) srand48(tmpseed); else seedrand(); /* Prepare to begin. */ starttime = presenttime(); N = 0; /* Loop, adding up Unif[0,1] random variables. */ while (1) { tmpval = drand48(); /* Discard simulation in progress if time up. */ if ( (N>0) && (presenttime() > starttime + runningtime) ) break; tot = tot + tmpval; N = N + 1; } printf("%f %d\n", tot/N, N); } seedrand() { struct timeval tmptv; int seed; gettimeofday (&tmptv, (struct timezone *)NULL); seed = (int) (tmptv.tv_usec - 1000000 * (int) ( ( (double) tmptv.tv_usec ) / ( (double) 1000000.0 ) ) ); srand48(seed); return(0); } long presenttime() /* Return present time in microseconds. */ { struct timeval tmp; gettimeofday (&tmp, (struct timezone *)NULL); return (tmp.tv_usec + 1000000 * tmp.tv_sec); }