/* ================================================================ example: use of the random number generator - rand from standard C++ library the code generates a) integer random numbers between i1 and i2 b) double random numbers between 0.0 and 1.0 AG ================================================================ */ #include #include #include #include #include #include using namespace std; int main () { int nmax = 10, i; /* define how many random numbers to generate */ int i1 = 1, i2 = 6; /* define interval of integer random numbers [i1 - i2] */ int irandom; double drandom; cout.precision(4); cout.setf(ios::fixed | ios::showpoint); /* for writing random numbers to a file */ ofstream file_1; file_1.open ("table01.dat"); file_1.precision(5); file_1.setf(ios::fixed | ios::showpoint); ofstream file_2; file_2.open ("table02.dat"); file_2.precision(5); file_2.setf(ios::fixed | ios::showpoint); /* Part 1: integer random numbers*/ cout << "integer random numbers between "<< i1<<" and "<< i2 << endl; srand (222); /* initial seed with some number */ // srand(time(NULL)); /* call time if you want to "randomize" the seed value */ for (i=0; i < nmax; i=i+1) { /* random number between i1 and i2 */ irandom = rand()%(i2-i1+1)+i1; /*number between i1 & i2*/ /* another method to generate a random number between i1 & i2*/ // irandom = i1 + int(1.0*(i2-i1+1)*rand()/(RAND_MAX+1.0)); cout << "i = " << irandom << endl; file_1 << setw(3) << irandom << endl; /* output to a file */ } cout << "The value of RAND_MAX is " << RAND_MAX << endl; /* Part 2: double float random numbers*/ cout << endl << "real random numbers between 0.0 and 1.0" << endl; // srand(time(NULL)); for (i=0; i < nmax; i=i+1) { drandom = 1.0*rand()/(RAND_MAX+1.0); /* random number between 0.0 and 1.0 */ cout << "d = " << drandom << endl; file_2 << " " << drandom << endl; /* output to a file */ } return 0; }