* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Download 3.8 Random Number Generation
Survey
Document related concepts
Transcript
Generating Random Numbers Textbook ch.6, pg. 356-367 1 Random Number Generation rand function (need to include <cmath>) 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) 2 Example Program #include <iostream> #include <cmath> using namespace std; void main() { int i; cout<<"Generating 10 random integers in the range 05:"<<endl; for (i=0; i<10 ;i++) cout<<" "<<rand()%6<<" "; cout<<endl; cout<<"Generating 10 random integers in the range 16:"<<endl; for (i=0; i<10 ;i++) cout<<" "<<1+rand()%6<<" "; cout<<endl; } 3 Example’s Program Output Generating 10 random integers in the range 0-5: 5 5 4 4 5 4 0 0 4 2 Generating 10 random integers in the range 1-6: 6 6 5 5 6 5 1 1 5 3 4 Shifting and Scaling •General shifting and scaling –Number = shiftingValue + rand() % scalingFactor –shiftingValue = first number in desired range –scalingFactor = width of desired range 5 Pseudorandom Numbers Calling rand() repeatedly Pseudorandom numbers Gives the same sequence of 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 6 Pseudorandom Numbers (ctd’) 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 <ctime>) Call the above statement ONCE in the beginning of the main program, before you call the rand() function. 7 Example Program #include <iostream.h> #include <cmath> #include <ctime> 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; } 8 Example’s Program Output Generating 10 random integers in the range 0-5 using time as seed: 4 3 5 5 5 2 4 2 4 1 9