// RandDemo.cc // usage: // RandDemo [ []] // example: // RandDemo (Run with default value of N and seed) // RandDemo 30 (Run with N=30 and default seed) // RandDemo 30 9237832 (Run with N=30 and seed=9237832) // features: // * uses random() to get a random integer // * gets parameters from command line // * uses ternary operator "q ? a : b" // * uses a function ("location") #include #include using namespace std; // declare functions, to be defined later int location( double x, double y ) ; #define ranf() \ ((double)random()/(1.0+(double)RAND_MAX)) // Uniform from interval [0,1) */ int main(int argc, char* argv[]) { int outcome, N=10, count_in=0 ; long seed=123 ; double fraction_in ; if(argc>1) { sscanf( argv[1], "%d", &N ) ; // put the first command-line argument in N } if(argc>2) { sscanf( argv[2], "%ld", &seed ) ; // put the 2nd argument in seed } // Write out a summary of parameters cout << "# " << argv[0] << " N=" << N << " seed=" << seed << endl ; // Initialise random number generator srandom(seed); // Perform N experiments. for(int n=1; n<=N; n++) { double x = ranf(); double y = ranf(); outcome = location(x,y); count_in += outcome ; //Integer variables must be converted (cast) for correct division fraction_in = static_cast(count_in)/n; cout << "Location" << outcome << "\t" << x << "\t" << y << "\t" << count_in << "\t" << n << "\t" << 4.0 * fraction_in << endl; } return 0; } int location( double x, double y ) { // returns 1 if (x,y) is in the unit circle, otherwise 0 // the ternary operator // (q) ? y : z // evaluates to y if q is true, else to z return ( x*x + y*y < 1.0 ) ? 1 : 0 ; }