Binomial Random Variables in C++

C++Server Side ProgrammingProgramming

Random variables are those variables that are an outcome of the outcomes of a process that has the probability of giving rise to multiple outcomes. For example, The variable denoting head or tail as an outcome on tossing a coin is a random variable.

A binomial random variable is a special type of random variable whose value is related to an event that has a fixed probability of an outcome in an event.

There are certain properties that are possessed by a binomial random variable that makes it special. These are a must for a variable to become a binomial random variable −

  • The total number of outcomes is fixed.

  • The outcome of the trail is either true or false, nothing in between.

  • The probability of occurrence is the same on each trail.

  • No two trails are dependent on each other.

Binomial random variable probability

The probability of success of an outcome is given by the formula −

P (x= k ) = n! / k! (n-k)! * pk * (1-p)n-k

Based on this probability of a binomial random variable, the number of occurrences of the variable in the sample space.

E[X] = np

The variance of success is given by Var[X] = np (1-p)

Example

 Live Demo

#include <iostream>
#include <cmath>
using namespace std;
int combination(int n, int r){
   if (r > n / 2)
   r = n - r;
   int answer = 1;
   for (int i = 1; i <= r; i++) {
      answer *= (n - r + i);
      answer /= i;
   }
   return answer;
}
float randombinomialProbability(int n, int k, float p){
   return combination(n, k)*pow(p, k)*pow(1 - p, n - k);
}
int main(){
   int n = 10;
   int k = 5;
   float p = 1.0 / 3;
   float binomialRandomVariable = randombinomialProbability(n, k, p);
   cout<<"Probability of "<<k;
   cout<<" heads when a coin is tossed "<< n;
   cout<<" times where probability of each head is "<<p;
   cout<<" is = "<<binomialRandomVariable<<endl;
}

Output

Probability of 5 heads when a coin is tossed 10 times where probability of each head is 0.333333 is = 0.136565
raja
Updated on 03-Jan-2020 07:01:33

Advertisements