//------------------------------------------------------------------- // buffon.cpp // // This program performs an automated simulation of the famous // Buffon Needle Problem: a needle 2-inches long is dropped at // random onto a floor made of 4-inch wide planks. How likely // is it that the needle will fall across a crack? We use the // built-in random number library function to simulate a drop, // and we "drop" our needle a great many times to estimate the // probability that the needle will fall across a crack on any // individual trial, based of the statistical Law of Averages. // // compile using: $ make buffon // execute using: $ buffon // // Note: This program was developed and tested using Linux 2.6. // // programmer: ALLAN CRUSE // written on: 31 AUG 2005 //------------------------------------------------------------------- #include // for printf() #include // for rand(), srand() #include // for sin() #include // for time() #define PI 3.14159 double random_real( void ) { return (double)rand() / (double)RAND_MAX; } int main( int argc, char **argv ) { printf( "\n\tDoing a simulation of Buffon's Needle Problem\n" ); int trials = 10000000; // we use ten million trials int across = 0; // initial value for counter srand( time( NULL ) ); // time seed for randomizing for (int i = 0; i < trials; i++) { double theta = PI * random_real(); double ydist = 4.0 * random_real(); if ( ydist < 2.0 * sin( theta ) ) ++across; } printf( "\n" ); printf( "\tNumber of needles dropped on floor = %8d \n", trials ); printf( "\tNumber of those that cross a crack = %8d \n", across ); double probability = (double)across / (double)trials; printf( "\n\tSo probability of crossing a crack is " ); printf( "%0.5f \n", probability ); double one_over_pi = (double)1.0 / (double)PI; printf( "\n\tFor a comparison: reciprocal of PI is " ); printf( "%0.5f \n\n", one_over_pi ); }