/* ================================================================ example: Non- uniform distribution use of the random number generator - rand from standard C++ library the code generates: double random numbers between xmin and xmax distributed with some probability w(x) AG ================================================================ */ #include #include #include #include #include #include using namespace std; double w(double); int main () { int nmax = 10000; /* define how many random numbers to generate */ double xmin=0.0, xmax=2.0, ymin, ymax; double x, y; int count = 0; cout.precision(6); cout.setf(ios::fixed | ios::showpoint); /* for writing random numbers to a file */ ofstream file_3; file_3.open ("table04.dat"); file_3.precision(5); file_3.setf(ios::fixed | ios::showpoint); ymax = w(xmin); /* may need to be redifined for other distribution */ ymin = w(xmax); /* may need to be redifined for other distribution */ cout << "ymin = " << ymin << " ymax = " << ymax << endl; srand(time(NULL)); for (double i=1; i <= nmax; i=i+1) { x = xmin + (xmax-xmin)*rand()/(RAND_MAX+1); y = ymin + (ymax-ymin)*rand()/(RAND_MAX+1); if (y > w(x)) continue; count = count + 1; file_3 << " " << x << endl; /* output to a file */ } cout << "count = " << count << endl; return 0; } /* Probability distribution w(x) */ double w(double x) { return exp(0.0-1.0*x*x); }