Bernoulli formula with more than one k

I want to make a program in which I calculate the probability with Bernoulli for multiple k's (for example if P(X<=2), so k is 0,1,2).

I have made the following program, but I do not understand why it does not work...
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
#include <iostream>
#include <cmath>
using namespace std;

int main()
{
   int n, k,anzahl;
   double p;
   cout << "n: ";
   cin >> n;
   cout << "p: ";
   cin >> p;
   cout<<"Anzahl k: ";
   cin>>anzahl;
   
   double log_answer,ergebniss=0;
   
   for(int n=0;n<anzahl;n++)
   {
       cout << "k"<<n<<" : "; 
   cin >> k;
   log_answer = k * log( p ) + ( n - k ) * log( 1.0 - p );
   for ( int nn = n, kk = k; kk; nn--, kk-- )
   {
       log_answer += log( (double)nn / kk );
   }
   ergebniss+=log_answer;
   }
   cout << "WK betrÃĪgt " << 100*ergebniss<<"%";
}
You shouldn't keep inputting new k values. Just input the maximum one.

Your program fails because it adds the logs of the probabilities to ergebniss, not the probabilities themselves. Use exp() to invert log().

You would be better writing a function:
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
#include <iostream>
#include <cmath>
using namespace std;


double Bernoulli( int n, double p, int k )
{
   double log_answer = k * log( p ) + ( n - k ) * log( 1.0 - p );
   for ( int nn = n, kk = k; kk; nn--, kk-- ) log_answer += log( (double)nn / kk );
   return exp( log_answer );
}


int main()
{
   int n, kmax;
   double p;
   cout << "Input the number of trials (n): ";   cin >> n;
   cout << "Input the probability of success on each trial (p): ";   cin >> p;
   cout << "Input the MAXIMUM number of successes (kmax): ";   cin >> kmax;
   
   double cumulative_probability = 0;
   for ( int k = 0; k <= kmax; k++ ) cumulative_probability += Bernoulli( n, p, k );

   cout << "P( result <= " << kmax << " ) is " << cumulative_probability << '\n';
}


Input the number of trials (n): 100
Input the probability of success on each trial (p): 0.3
Input the MAXIMUM number of successes (kmax): 35
P( result <= 35 ) is 0.883921
Last edited on
Topic archived. No new replies allowed.