/* File: random.c */ /* ********************************************************************* ALTERNATING BIT AND GO-BACK-N NETWORK EMULATOR Revised version of code by J.F. Kurose From the companion website for _Computer Networking: A Top-Down Approach Featuring the Internet_ by J.F. Kurose and K. W. Ross (c) 2001 by Addison Wesley Longman Based on document at (as of 02 July 2002) ********************************************************************* */ /************** PSEUDORANDOM NUMBERS ******************/ /* The next set of routines deal with random numbers */ /******************************************************/ /*------------*/ /* test_rand */ /* *----------------------------------------------------*/ /* */ /*-----------------------------------------------------------------*/ void test_rand(void){ int i; float sum; float avg; #define RANDOM #ifdef RANDOM srand((unsigned int)time((time_t *)NULL)); #else srand(42); /* same simulation every time */ #endif /* test random number generator for students */ sum = 0.0; for (i=0; i<1000; i++) { sum += jimsrand(); /* jimsrand() should be uniform in [0,1] */ } avg = sum/1000.0; if (TRACE > 3) { printf("%*sTEST_RAND: sum = %f, avg == %f\n\n",INDENT,"", sum, avg); } if (avg < 0.25 || avg > 0.75) { printf("\n\n**SIMULATION HALTED**\n"); printf("It is likely that random number generation on your machine\n"); printf("is different from what this emulator expects. Please read\n"); printf("the jimsrand() function in the emulator code. Sorry. \n"); if (TRACE) { printf("%*sTEST_RAND: using rand() with ", INDENT, ""); #ifdef RANDOM printf("random"); #else printf("constant"); #endif printf(" seed\n"); printf("%*sTEST_RAND: sum = %f, avg == %f\n",INDENT,"", sum, avg); } exit(EXIT_FAILURE); } } /* test_rand() */ /*------------*/ /* jimsrand */ /* *----------------------------------------------------*/ /* */ /* Return a float in range [0,1]. */ /*-----------------------------------------------------------------*/ float jimsrand(void) { return ((float)rand())/RAND_MAX; } /* jimsrand() */ /* EOF (random.c) */