//------------------------------------------------------------------- // e_as_mean.cpp // // This program revises our earlier 'eulernum.cpp' demo so as // to exhibit a graph of the probability distribution for the // number of values from [0,1] needed to get a sum above one. // // to compile: $ g++ e_as_mean.cpp -o e_as_mean // to execute: $ ./e_as_mean // // NOTE: The program takes several seconds to finish running. // // programmer: ALLAN CRUSE // written on: 17 FEB 2011 //------------------------------------------------------------------- #include // for printf() #include // for drand48(), srand48() #include // for time() #define N_TRIALS 100000000 // one hundred million double summands( void ) { double rep = 0.0, sum = 0.0; do { sum += drand48(); rep += 1.0; } while ( sum < 1.0 ); return rep; } #define MAX_N 10 int main( int argc, char **argv ) { printf( "\n An introduction to Euler's Number e = 2.718...\n\n" ); srand48( time( NULL ) ); double total = 0.0; double tries = 0.0; long freq[ MAX_N ] = { 0 }; for (int i = 0; i < N_TRIALS; i++) { double count = summands(); int index = (int)count; if ( index < MAX_N ) freq[ index ] += 1L; total += count; tries += 1.0; switch ( i+1 ) { case 1000: case 10000: case 100000: case 1000000: case 10000000: case 100000000: printf( " After %u trials, ", i+1 ); printf( "the average number of summands " ); printf( "was %1.3f \n", total / tries ); } } printf( "\n" ); double prob[ MAX_N ]; for (int i = 0; i < MAX_N; i++) prob[ i ] = (freq[ i ]*1.0) / (tries*1.0); printf( " Graph of the probability distribution" ); printf( " for the number of summands \n\n" ); for (int i = 1; i < MAX_N; i++) { int n = 100.0 * prob[i]; printf( " prob[%d]=%1.5f ", i, prob[i] ); for (int j = 0; j < n; j++) printf( "*" ); printf( "\n" ); } printf( "\n" ); }