Random Number Generator
Using Software We can generate random number by: 1- table 2- hardware 3-- software Function to generate RN by SW is: 1-rand 2- srand
algorithmic (software) generators Algorithmic generators are widely accepted because they meet all of the following criteria. randomness - output passes all reasonable statistical tests of randomness controllability - able to reproduce output, if desired portability - able to produce the same output on a wide variety of computer systems efficiency - fast, minimal computer resource requirements documentation - theoretically analyzed and extensively tested
Rand function It’s advantage that it produce the same number. They solve this drawback by using (srand) function
Code by (rand) function 1 2 // Shifted, scaled integers produced by 1 + rand() % 6. 3 #include 4 5 using std::cout; 6 using std::endl; 7 8 #include 9 10 using std::setw; #include // contains function prototype for rand int main() 15 { 16 // loop 20 times 17 for ( int counter = 1; counter <= 20; counter++ ) { // pick random number from 1 to 6 and output it 20 cout << setw( 10 ) << ( 1 + rand() % 6 ); // if counter divisible by 5, begin new line of output 23 if ( counter % 5 == 0 ) 24 cout << endl; } // end for structure
27 28 return 0; // indicates successful termination } // end main
(Srand) function It used to solve the disadvantage of (rand) function Advantage of (srand) is: 1- every time it run it produce different number The disadvantage of (srand) is: 1- the user must enter the variable to start generator.
Code by (srand) function
Develop to use (srand) function To prevent the user from entering the variable they make enhancement to (srand) by using (srand(time(0))) To use this function we must add the library (time.h)
Srand(NULL)function
Advantage: Every time generate random number without intervention from the user