/* estPi.cpp * * This program calculates Pi using random numbers. * * Bruce M. Bolden * October 14, 1997 * --------------------------------------------------------- */ #include #include #include #include // Prototypes double GetXY(); void GetXY( double& x, double& y ); int IsInside( double x, double y ); void InitRandomNumberGenerator(); int main() { //InitRandomNumberGenerator(); char ans = 'y'; // response to continuation question do { int nHits = 0; // number of "hits" int nTries; // number of attempts double x, y; // coordinates of random point // Prompt for number of attempts cout << "Number of tries: "; cin >> nTries; // Generate points, test if inside unit circle for( int i = 0; i < nTries ; ++i ) { //x = GetXY(); //y = GetXY(); GetXY( x, y ); // pass by reference if( IsInside( x, y ) ) ++nHits; } cout << "nHits: " << nHits << endl; // Show results double pi = 4.0 * nHits/nTries; cout << " Pi: " << pi << endl; // Ask if user wants to continue cout << "Again [y/n]? "; cin >> ans; } while( ans != 'n' && ans != 'N' ); return 0; } /* GetXY() * * Generate a random value between 0.0 and 1.0. */ double GetXY() { double rVal = double(rand()) / double(RAND_MAX); //double rVal = double(rand() % 101) / 100.0; //cout << rVal << endl; // check values return rVal; } void GetXY( double& x, double& y ) { x = double(rand()) / double(RAND_MAX); y = double(rand()) / double(RAND_MAX); // Old method //x = double(rand() % 101) / 100.0; //y = double(rand() % 101) / 100.0; } /* IsInside * * Test if a point (x,y) lies inside the unit circle */ int IsInside( double x, double y ) { if( x*x + y*y <= 1.0 ) return 1; return 0; } /* InitRandomNumberGenerator * * Initialize random number generator. */ void InitRandomNumberGenerator() { /* Seed the random-number generator with current time so * that the numbers will be different each time program is run. */ srand( (unsigned)time( NULL ) ); }