Advertisement
Guest User

TB's proposed coin flip game

a guest
Dec 29th, 2010
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.65 KB | None | 0 0
  1. #include <stdio.h>
  2. #include "utilfun.h"
  3.  
  4. int
  5. main( int argc, char *argv[] ) {
  6.  
  7.   int mm, nn;
  8.   int numwon, numlost;
  9.   int tt, ttall, hhall;
  10.   int ii, jj;
  11.   double fract, fractavg;
  12.  
  13.   seedrand(); // seed random number generator with epoch elapsed time
  14.  
  15.   mm = 1e6; // number of games to simulate
  16.   nn = 1e4; // number of trials to simulate
  17.  
  18.   ttall = 0;
  19.   hhall = 0;
  20.   numwon = 0;
  21.   numlost = 0;
  22.   fractavg = 0.0;
  23.  
  24.   printf("\n");
  25.   printf("%20.0e number of games to play\n", (double) mm);
  26.   printf("%20.0e number of trials per game\n", (double) nn);
  27.   printf("\n");
  28.   printf("Simulating...\n");
  29.   printf("\n");
  30.   fflush(stdout);
  31.  
  32.   for ( ii = 0; ii < mm; ++ii ) {
  33.     fract = 0.0; // fraction of tails
  34.     tt = 0;      // number of tails flipped
  35.     for ( jj = 0; jj < nn; ++jj ) {
  36.       while ( ranf() < 0.5 ) // ranf() -> [0,1) uniform; flip until heads
  37.         ++tt;  // while flipping tails
  38.     } // for jj
  39.     ttall += tt;
  40.     hhall += nn; // one head flipped per trial
  41.     fract += (double) tt / (tt + nn); // fraction of tails flipped
  42.     fractavg += fract;
  43.     if ( fract < 0.5 ) ++numwon;  // guess stop on heads
  44.     if ( fract > 0.5 ) ++numlost; // guess stop on tails
  45.   } // for ii
  46.  
  47.   fractavg /= mm;
  48.  
  49.   printf("%20.12e average fraction T/(T+H)\n", fractavg);
  50.   printf("%20d total number of tails flipped\n", ttall);
  51.   printf("%20d total number of heads flipped\n", hhall);
  52.   printf("%20d number won by strategy guesser\n", numwon);
  53.   printf("%20d number undecided by strategy guesser\n", mm - numwon - numlost);
  54.   printf("%20d number lost by strategy guesser\n", numlost);
  55.   printf("\n");
  56.  
  57.   return(0);
  58. } // main
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement