// Horstman and Budd page 142 Buffon's Needle Simulation // Improved by RJBotting // Calculate PI rather than use a hard to memorize value // Simplify calculating yhigh // Factor out 1.0/RAND_MAX #include #include #include #include using namespace std; int main() { /* set seed of random number generator */ srand(time(0)); const double SCALE = 1.0/RAND_MAX; int NTRIES = 10000; const double PI = 4*atan(1); // From Dr. Keith Schubert int hits = 0; for (int i = 1; i <= NTRIES; i++) { double ylow = 2 * (rand() * SCALE); double yhigh = ylow + sin( (rand() * SCALE) * PI ); if (yhigh >= 2) hits++; } cout << "Tries / Hits = " << NTRIES * (1.0 / hits) << "\n"; return 0; }