Binomial Distribution with a coin flip

Hello! I am needing some help with getting this code to work. I know this is a homework assignment, but I am unable to get everything working. Our teacher gave us a binomial distribution assignment to calculate a coin flip.

My problem is that he is wanting us to calculate the probability of tossing a coin 10 times and getting exactly 0,1,2,3, ect. heads. Success is 0.5 and fail is 0.5 chance. He wants us to store the probability in an array and to use a "for" loop from 0-10 where r is the number of successes. I have slowly written step-by-step the different calculations, first the denominator then the numerator and so forth.

The binomial distribution code is:

p(x)=N!/X!(N-X)!*(0.5)^x(1-0.5)^N-X

I have gotten the code to show the calculations for each section so far except the exponent array. I need to store these values in an array I assume because they have to be accessed later on so since the problem has you raise the value of 0.5 to N-x, the values need to descrease starting with 10 is what I figured so I would go from 10 to 0 backwards, store that value and then call it when I calculated the answer, but I am getting a conflicting error saying "invalid types double [11] [double]" where I calculate the exponent.

Please remember this is my very first year of C++ and I just started the class this fall. Any hints would be appreciated. I have read my chapters in my book and I am racking my brain about this code. it is due today at midnight and I have been working on it for days now. Please, any help or hints would be amazing. The teacher and other students are unhelpful and this is an online class.

Here is my code so far, it is a work in progress.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
#include <iostream>  //to use cout and cin and endl// allows using cout without std::cout

#include <string> // to use string data type

#include <cstring> //to use strlen, strcmp, strcpy

#include <cmath>   //for pow function,sqrt,abs

#include <iomanip>  // for set precision, setw,

#include <fstream> //for file input

#include <cassert> // to use assert  to disable place before #define NDEBUG

#include <cstdlib>//for random numbers, exit function

#include <ctime>//time function used for rand seed

#include <cctype>  // for toupper, tolower

#include <algorithm>

#include <locale.h>

#include <stdio.h>

#include <math.h>




using namespace std;

 
int main()
{
      double factorial=1.0;  //an integer would be too small

    int row =1;
    
    const double N=3628800;
    
    double firstPart=0.0;
    
    int counter=1;
    
    double denominator=0;
    
    double second[11]={0.0};
    
    double third=0.0;
    
    int r=0;
    
    double exponent[11]={0.0};
    
    double x=10.0;
    
    double fourthPart=0.0;
    
    double answer[11]={0.0};
    
    

    double factorialarray[30]={0};//rows 0-29

    cout<<fixed<<setprecision(0);

    //calculate factorials 0-10

    for(row=0;row<=10;row++)//outer loop //here is where I calculate the factorials needed for later on. This section was written by the teacher.

    {

        factorial=1.0;

        for(counter=row;counter>=1;counter--)

        {

            factorial=factorial*counter;

        }//bottom of inner loop


        factorialarray[row]=factorial;

       

    }//bottom of outer loop
   
    //My code starts here 
   //We have to have a header for r and for the decimal probability.
    cout<<"Number of flips             Probability of Heads"<<endl;
    cout<<" "<<endl;
    //here is where I am calculating (0.5)^N-X
    for (double x=10.0;x>0.0;x--)
             {
          exponent[x]=pow(0.5,x);//error here stating the double [11] [double] problem
          
          
        //Start of positive loop to do everything together          
       for (int r=0;r<=10;r++)

            {
        denominator=factorialarray[r]*factorialarray[10-r]; //denominator calculation
        firstPart=N/denominator; 
        second[row]=pow(0.5,r); 
        answer=firstPart*second[row]*exponent[x]; //I made a fourth part, but the calculations were giving me higher numbers
        
        cout<<setw(4)<<r<<setw(15)<<setprecision(4)<<answer<<endl;

                }
   
        
    }
       
      
 
return 0;
}
Last edited on
I know I need to call the array whenever the ! sign is showing for the factorials

We do not call array. We access element of the array.

Look at the printarray(). It does show the factorials from the array, does it not?
How would you get the factorial of 4? Is it stored in factorialarray[4]?

The math notation is more compact than the C++ syntax.
N!/X!(N-X)!*(0.5)^x(1-0.5)^N-X

At least the multiplication is missing:
N! / X! * (N-X)! * 0.5^X * (1-0.5)^(N-X)
The k! is not C++. factorialarray[k] would be.

0.5^X is not C++ either.
You do have #include <cmath> //for pow function
Check the pow function: http://www.cplusplus.com/reference/cmath/pow/
Yes, sorry I mean to access the element of the array. Yes I do know that ^ is not c++ code. You use pow(n,2.0). I am trying to figure out the most efficient way of writing the formula in C++ code.

The code I posted was only to assign functions to an array. I have not been able to write the code for the program I need.
I am still needing help on this code, I did most of the work already. Just need a push in the right direction or some small syntax error I am making. Arrays are a brand new topic for our class so that shows what a big assignment this is with little previous experience. Thank you to anyone who could help me.
Please don't edit your previous posts, it makes it very unclear as to what progress has been made and what problems still exist.

Here are your actual errors and warnings,
 In function 'int main()':
99:21: error: invalid types 'double [11][double]' for array subscript
109:48: error: invalid types 'double [11][double]' for array subscript
51:12: warning: unused variable 'third' [-Wunused-variable]
53:9: warning: unused variable 'r' [-Wunused-variable]
57:12: warning: unused variable 'x' [-Wunused-variable]
59:12: warning: unused variable 'fourthPart' [-Wunused-variable]


1
2
3
4
    for (double x=10.0;x>0.0;x--)
             {
          exponent[x]=pow(0.5,x);//error here stating the double [11] [double] problem
          

If your for loop is only going through integer values (10, 9, 8...), then don't use double, because array indices need to be integers. If you need to use x as a double, cast it to a double using static_cast<double>(x).

answer=firstPart*second[row]*exponent[x]; //I made a fourth part, but the calculations were giving me higher numbers
You have answer as an array. Is this intended? If so, you can't just assign to the array itself, you have to assign to an index of the array
answer[some_index] = some_value;
Last edited on
residentevil35 wrote:
The binomial distribution code is:
p(x)=N!/X!(N-X)!*(0.5)^x(1-0.5)^N-X


OK, think about the maths first.

Take the part:
(0.5)^x(1-0.5)^N-X
otherwise known as (1/2)N or, in c++ code
pow(0.5,N);
You will notice that it is independent of x (for an unbiased coin) and so the same for every element of the array.

The other bit of the product is N!/X!(N-X)!. It's got some posh terminology NCX but for now let's call it f[X]. Then,
f[0] = 1
f[1] = f[0] * (N  ) / 1
f[2] = f[1] * (N-1) / 2
f[3] = f[2] * (N-2) / 3
f[4] = f[3] * (N-3) / 4
....

Spot the pattern?
Where there's a pattern there's a for-loop. So you could build your initial array term by term like this, then cycle through again and multiply by the probability part. You could even call your array f[] ...

The one thing that you DON'T want to do is work out large factorials.
Last edited on
Sorry I edited my first post. The reason being that I could not find out how to delete it, didn't want to make two of the same thing, and the last post had no code. I didn't even know where to start then.

I am so close to getting this solved. Yes we have to write the answer to an array. My problem is accessing the values stored in exponent and multiplying them by the for loop for r. It is displaying the exponents correctly, but upside down.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
#include <iostream>  //to use cout and cin and endl// allows using cout without std::cout

#include <string> // to use string data type

#include <cstring> //to use strlen, strcmp, strcpy

#include <cmath>   //for pow function,sqrt,abs

#include <iomanip>  // for set precision, setw,

#include <fstream> //for file input

#include <cassert> // to use assert  to disable place before #define NDEBUG

#include <cstdlib>//for random numbers, exit function

#include <ctime>//time function used for rand seed

#include <cctype>  // for toupper, tolower

#include <algorithm>

#include <locale.h>

#include <stdio.h>

#include <math.h>


using namespace std;
using std::array;


   float exponent[11]={0.000976562,0.00195312,0.00390625};
 
   float base=0.5;
 
   float result=0.0;
 
  double factorial=1.0;  //an integer would be too small

    int row =1;
    
    const double N=3628800;
    
    double firstPart=0.0;
    
    int counter=1;
    
    double denominator=0;
    
    double second[11]={0.0};
    
    double third=0.0;
    
    int r=0.0;

    double fourthPart=0.0;
    
    double answer=0.0;
    
    
   
    double factorialarray[30]={0};//rows 0-29

   


int main()
{
 

    
    for(row=0;row<=10;row++)//outer loop

    {

        factorial=1.0;

        for(counter=row;counter>=1;counter--)

        {

            factorial=factorial*counter;
           
                   }//bottom of inner loop


        factorialarray[row]=factorial;

         }//bottom of outer loop
    
    

    cout<<"Number of flips             Probability of Heads"<<endl;
    cout<<" "<<endl;
       
        
        for (int x=10;x>0;x--)
     {
        result = pow(base, x);
        exponent[x]=result; //trying to get these values to multiply with the r values. 
                                     //They do it, but it needs to be backwards. 

         cout<<setw(10)<<exponent[x]<<endl;
    
                          }
                          
       for ( int r=0;r<=10;r++)

            {
        denominator=factorialarray[r]*factorialarray[10-r];
        firstPart=N/denominator;
        second[row]=pow(0.5,r);
        answer=firstPart*second[row];
        
        

                
    cout<<setw(4)<<r<<setw(15)<<firstPart<<setw(22)<<setprecision(4)<<answer<<setw(20)<<endl; 
    
       }
    
return 0;
}
          



My output:

0 1 1
1 10 5
2 45 11.25
3 120 15
4 210 13.12
5 252 7.875
6 210 3.281
7 120 0.9375
8 45 0.1758
9 10 0.01953
10 1 0.0009766
Topic archived. No new replies allowed.