// RandDemo.cc // features: // * uses random() to get a random integer // * gets interactive user input // * uses ternary operator "q ? a : b" #include #include #include using namespace std; #define ranf() \ ((double)random()/(1.0+(double)RAND_MAX)) // Uniform from interval [0,1) */ // random() typically makes an integer in the range 0..0x7fffffff int main() { int outcome, N=0, count_in=0 ; double fraction_in ; char *position , in[]="IN", out[]="OUT" ; // Initialise random number generator with value of system time. srandom(time(NULL)); // Get user input in correct range. do { cout << "# Input the number of experiments: "; cin >> N; } while(N<1); // Perform N experiments. for(int n=1; n<=N; n++) { double x = ranf(); double y = ranf(); outcome = ( x*x + y*y > 1.0 ) ? 0 : 1 ; position = ( x*x + y*y > 1.0 ) ? out : in ; if(outcome==1) count_in++; cout << position << "\t" << x << "\t" << y << "\t" << count_in << "\t" << n << endl; } //Integer variables must be converted (cast) for correct division fraction_in = static_cast(count_in)/N; // Output results cout << "# Proportion of outcomes 'in' " << fraction_in << endl; // Output results cout << "# pi-hat = " << 4.0 * fraction_in << endl; return 0; }