Thread: Binomial Simulation

  1. #1
    Registered User
    Join Date
    Nov 2010
    Posts
    29

    Question Binomial Simulation

    I have a project for school in which I have to write a program based on probability where a "coin" is flipped 10,000 times. The 10,000 flips are divided into 1,000 trials of 10 flips each. I'm stuck on a couple bits of code. The following is what I have:

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    int main(void){
      int flips[10], numHeadsThisTime, trialNumber, flipNumber;
      
      for (trialNumber = 0; trialNumber < 1000; trialNumber++){
          //flips[10] and increment (#3)
          for (flipNumber = 0; flipNumber <10; flipNumber++){
              int thisSample; 
              thisSample = rand();
              if (thisSample < RAND_MAX/2){
                             //heads 
                             }
              if (thisSample > RAND_MAX/2){
                             //tails
                             }
    }}
        system("pause");    
        return 0;
    }
    I need to figure out what code goes where I have the comment (//flips[10] and increment (#3)). My teacher says to "Between each trial (which means inside the outer loop and outside the inner loop): Switch on the number of heads for this trial, with a case for 0, 1, 2 … 10. Within each case of the switch, add one to the appropriate counter. For example, in the case of the switch for 3 heads, add 1 to the relevant outcome counter variable. In my example, this would bean threeOfTen = threeOfTen + 1 or some other way of adding one to the counter ( ++ will also work). If you’re using an array to hold the heads counts, you can use the number of heads (out of 10) as
    the subscript into that array and increment the array element. Be sure to reset the number of heads to zero, after each set of ten flips (between the outer and inner loops) so that numHeadsThisTime will only range from 0 to 10, and not keep counting
    heads across trials." I'm using the array "flips[10]." Any hints of what I need to put here?

    I'm also not sure what to put in after the "if" statements. I think this is where I generate my graph of results. I need to "After these loops have run create code to generate a graph of your results. The Chapter Notes for Chapter 7 show an example of making a horizontal bar chart using printf and printing asterisks. You can use that as a starting point. Note that you will need to scale the value of each count so that a sane number of asterisks are printed. You can probably just divide each count by a constant to get how many stars to print. You’re free to produce any sort of graph that suits your fancy, as long as it accurately conveys the information from your simulation. Possible embellishments I left out include labeling the bars and adding counts to the ends giving the values of each counter. But these alterations are optional and you can receive full credit for the project with output no more detailed than mine."

  2. #2
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    So you want to build an array that, when you're done, contains the following:
    Code:
    flips[0] = /* number of trials where you got 0 heads */
    flips[1] = /* number of trials where you got 1 heads */
    ...
    flips[10] = /* number of trials where you got 10 heads */
    Thus, you need flips[11], so you have indexes 0..10. Also, the total of all 11 elements in that array should always add up to the number of trials, 1000.

    I think your "what should i put here" comment belongs after the inner for loop. A bit of pseudo code would look like this:
    Code:
    int flips[FLIPS_PER_TRIAL+1], thisSample, numHeadsThisTime, trialNumber, flipNumber;
    
    // initialize flips to all zeros
    
    for trialNumber from 0 to NUM_TRIALS - 1
        numHeadsThisTime = 0;
        for flipNumber from 0 to FLIPS_PER_TRIAL - 1
            thisSample = rand();
            if (thisSample < RAND_MAX/2) {
                numHeadsThisTime++;
            }
        }
        flips[numHeadsThisTime]++;
    }
    
    /* print out something like this (10 trials per star)
    0: **
    1: ****
    ...
    5: **************
    ...
    10: *
    You should see something roughly symmetric, with the longest set of stars in the middle, and the smallest on the ends
    */

  3. #3
    Registered User
    Join Date
    Nov 2010
    Posts
    29
    I've got the following so far but am sort of confused what I am doing with the "flips[numHeadsThisTime]++" and really confused how I am supposed to print this out.


    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    int main(void){
      int flips[11], numHeadsThisTime, trialNumber, flipNumber;
      
      for (trialNumber = 0; trialNumber < 999; trialNumber++){
          numHeadsThisTime = 0;
          for (flipNumber = 0; flipNumber <9; flipNumber++){
              int thisSample, thisTrial; 
              thisSample = rand();
              if (thisSample < RAND_MAX/2){
                             numHeadsThisTime++;
                             }
     
      }
      flips[numHeadsThisTime]++;
      }
      
      
      
        system("pause");    
        return 0;
    }

  4. #4
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    We're counting the likelihood of flipping a coin 10 times and getting a certain number of heads. Of course, 5 heads and 5 tails is most likely, but we could get zero heads, or just 1.

    flips[numHeadsThisTime]++ increments the count of how many trials (of flipping 10 coins) resulted in exactly numHeadsThisTime heads.

    As for printing, we tried this coin flipping thing 1000 times. The most likely scenario is 5 heads and 5 tails. It should account for a good 20% or more of the trials. As an example, lets say it was 200 trials. We don't want to print 200 asterisks, since that would span multiple lines and look ugly, so we print, say, 20 asterisks for 200 trials. We do this by dividing the number of trials by 10. Some more pseudo code:
    Code:
    for i from 0 to 10 {
        // print i since it represents trials that resulted in 'i' heads
        for j from 0 to flips[i] / 10 {
            // print 1 asterisk since this represents one asterisk per 10 trials (/ 10 in the line above)
        }
        // print a new line for good measure
    }
    Again, make sure you initialize flips at the beginning of you program, with a loop like so:
    Code:
    for i from 0 to 10
        flips[i] = 0

  5. #5
    Registered User
    Join Date
    Nov 2010
    Posts
    29
    Is "i" "flipNumber" here or are these two new loops?

    Is flips[i] supposed to be flips[flipNumber]?

  6. #6
    Registered User
    Join Date
    Nov 2010
    Posts
    29
    This is what I am having a hard time wrapping my head around: each trial has ten flips of the coin and the number of heads that come up store into "numHeadsThisTime." How do I then take that number stored and place it as an occurrance in the corresponding array element (seven heads into flips[7] )?
    Last edited by quintenmater; 12-04-2010 at 06:57 PM.

  7. #7
    Registered User
    Join Date
    Nov 2010
    Posts
    29
    Ahhh- flips[numHeadsThisTime]++ increments the occurrences into the arrays doesnt it? now I just need to figure out how to print out what is within each array but only one star for each ten occurrances

  8. #8
    Registered User
    Join Date
    Nov 2010
    Posts
    29
    Sorry, not meaning to leave a bunch of comments just slowly figuring things out. Why doesn't the following program work:

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    
    int main(void){
      int numHeadsThisTime, trialNumber, flipNumber, flips[11];
      //initialize array to all 0's
      for (int i=0; i<10; i++){
          flips[i]=0;}
      
      //trials    
      for (trialNumber = 0; trialNumber < 999; trialNumber++){
          numHeadsThisTime = 0;
          for (flipNumber = 0; flipNumber <9; flipNumber++){
              int thisSample, thisTrial; 
              thisSample = rand();
              if (thisSample < RAND_MAX/2){
                             numHeadsThisTime++;
                             }
      }
      //increment each array for each occurance
      flips[numHeadsThisTime]++;
      }
       
       //print
       for (int i=0; i<10; i++){
    	   for(int j=0; j<flips[i]/10; j++){
    		        printf("*");}
    		        printf("\n");
                    }
      
        system("pause");    
        return 0;
    }

  9. #9
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    I compiled and ran your code and it mostly worked. Actually, you're code is spot on except for a few issues with your loops. If you declare an array flips[11], that means there are 11 spots in there. The indexes of these spots range from 0 to 10 inclusive. So the loops you use to run through the elements of flips (initialization and printing) need to use <= 10 instead of < 10, like so:
    Code:
    for (i = 0; i <= 10; i++)
    Also, you're off by one on your flipNumber loop. You need to be < 10 there, since that means i will have the values 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9...a total of 10 values or flips.

    The only other thing I would add is this:
    Code:
       //print
       printf("Each star represents 10 trials\n");
       for (int i=0; i<10; i++){
               printf("%2d: ");
    	   for(int j=0; j<flips[i]/10; j++){
    Just to clarify what the distribution represents (trials per star and heads per trial).

  10. #10
    Registered User
    Join Date
    Nov 2010
    Posts
    29
    It works- just wondering why its only printing 999 trials. New code:
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    int main(void){
      int numHeadsThisTime, trialNumber, flipNumber, flips[11];
      //initialize array to all 0's
      for (int i=0; i<10; i++){
          flips[i]=0;}
      
      //trials    
      for (trialNumber = 0; trialNumber < 1000; trialNumber++){
          numHeadsThisTime = 0;
          for (flipNumber = 0; flipNumber < 10; flipNumber++){
              int thisSample, thisTrial; 
              thisSample = rand();
              if (thisSample < RAND_MAX/2){
                             numHeadsThisTime++;
                             }
      }
      //increment each array for each occurance
      flips[numHeadsThisTime]++;
      }
       
       //print
       printf("Binomial Simulation.\n");
       for (int i=0; i<10; i++){
           printf("%i", flips[i]);
    	   for(int j=0; j<flips[i]/10; j++){
    		        printf("*");}
    		        printf("\n");
                    }
      
        system("pause");    
        return 0;
    }

  11. #11
    Registered User
    Join Date
    Nov 2010
    Posts
    29
    Thanks I made those changes but what does printf("%2d: "); do

  12. #12
    Registered User
    Join Date
    Nov 2010
    Posts
    29
    The numbers aren't changing now when I recompile. I'm getting the same results each time. Any reason?

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    int main(void){
      int numHeadsThisTime, trialNumber, flipNumber, flips[11];
      //initialize array to all 0's
      for (int i=0; i<=10; i++){
          flips[i]=0;}
      
      //trials    
      for (trialNumber = 0; trialNumber < 1000; trialNumber++){
          numHeadsThisTime = 0;
          for (flipNumber = 0; flipNumber < 10; flipNumber++){
              int thisSample, thisTrial; 
              thisSample = rand();
              if (thisSample < RAND_MAX/2){
                             numHeadsThisTime++;
                             }
      }
      //increment each array for each occurance
      flips[numHeadsThisTime]++;
      }
       
       //print
       printf("Binomial Simulation.\n");
       printf("Each star represents 10 trials\n");
       for (int i=0; i<=10; i++){
           printf("%i heads:",i );
           printf("%i", flips[i]);
    	   for(int j=0; j<flips[i]/10; j++){
    		        printf("*");}
    		        printf("\n");
                    }
      
        system("pause");    
        return 0;
    }

  13. #13
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    Haha, I just looked and realized that I forgot to put a variable in there. It should be printf("%2d: ", i). That probably helped confuse you a bit. You want i in there, not flips[i] as your most recent post shows.

    %d is just for printing integers in decimal format (vs hex for example). It's like %i, but it just happens to be what I learned to use...old habits. The 2 means it forces the number to take up 2 characters (right justified, filling in with spaces). This is just to line up the start of your stars, since your last row will need 2 digits to display 10 and it will be off 1 character from the rest of the rows, since they're single digit.

    As for your problem, when I ran your code, I only got 997 instead of 999, then I realized you missed one of my comments above. Your loops for initialization and printing need to be for (i = 0; i <= 10; i++). That <= is critical, since otherwise you're not initializing or printing out the case that all 10 flips in a trial resulted in heads.

    A couple other small things. You can remove thisTrial since it's never used. You should also seed the rand function so you don't get the same results every time. You can just put srand(time(NULL)); as the first statement in main. Make sure you include the right headers for this (I think it's stdlib.h and time.h).

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. fork, execv, spawn, or something else?
    By DavidP in forum C++ Programming
    Replies: 8
    Last Post: 01-26-2009, 04:25 PM
  2. Role of c++ in simulation software
    By CChakra in forum C++ Programming
    Replies: 9
    Last Post: 11-18-2008, 02:36 AM
  3. Help with time simulation assignment
    By rakan in forum C++ Programming
    Replies: 3
    Last Post: 10-31-2006, 11:39 AM
  4. A binomial queue (binomial tree) question.
    By NightWalker in forum C Programming
    Replies: 2
    Last Post: 10-27-2003, 08:25 AM
  5. Replies: 1
    Last Post: 01-30-2002, 01:04 PM