1 Generating Random Numbers Textbook ch.6, pg
2 Random Number Generation rand function (need to include ) i = rand(); Generates unsigned integer between 0 and RAND_MAX (usually 32767) Scaling and shifting Examples i = rand() % 6; generates a number between 0 and 5 (scaling) i = 1 + rand() % 6; generates a number between 1 and 6 (the “+ 1” makes the shift by 1)
3 Example Program #include using namespace std; void main() { int i; cout<<"Generating 10 random integers in the range 0- 5:"<<endl; for (i=0; i<10 ;i++) cout<<" "<<rand()%6<<" "; cout<<endl; cout<<"Generating 10 random integers in the range 1- 6:"<<endl; for (i=0; i<10 ;i++) cout<<" "<<1+rand()%6<<" "; cout<<endl; }
4 Generating 10 random integers in the range 0-5: Generating 10 random integers in the range 1-6: Example’s Program Output
5 General shifting and scaling –Number = shiftingValue + rand() % scalingFactor –shiftingValue = first number in desired range –scalingFactor = width of desired range Shifting and Scaling
6 Calling rand() repeatedly Gives the same sequence of numbers Pseudorandom numbers Preset sequence of "random" numbers Same sequence generated whenever program runs To get different random sequences Provide a seed value (unsigned integer value) Like a random starting point in the sequence The same seed will give the same sequence srand(seed); Used before rand() to set the seed Pseudorandom Numbers
7 OR can use the current time to set the seed No need to explicitly set seed every time srand( time( 0 ) ); The time function returns the current time in seconds (need to include ) Call the above statement ONCE in the beginning of the main program, before you call the rand() function. Pseudorandom Numbers (ctd’)
8 Example Program #include using namespace std; void main() { int i; srand(time(0)); //this generates the first seed value cout<<“Generating 10 random integers in the range 0-5 using time as seed:"<<endl; for (i=0; i<10 ;i++) cout<<" "<<rand()%6<<" "; cout<<endl; }
9 Generating 10 random integers in the range 0-5 using time as seed: Example’s Program Output