Binomial Distribution In C++

In this tutorial, we shall learn to compute the integers according to the binomial discrete distribution in C++. So, first, we need to know what is a binomial distribution.
The binomial distribution gives the discrete probability distribution P( k|n ) of obtaining exactly ‘k’ successes out of ‘n’ Bernoulli trial. A Bernoulli trial is an event in which the probability of success is ‘p’ whereas the probability of failure is ‘q=1-p’.

So, P( k|n )= P(k out of n) =  (n!/(k! (n-k)!)) pk(1-p)(n-k)
where n is the total no of trials and k is no of successes we require to calculate.

The Algorithm And C++ Code for Binomial Distribution

The operator function generates a new random number. The max returns the least upper bound of the range given by the operator function, for which binomial distribution is the distribution parameter k. The min returns the greatest lower bound of the range given by member operator function, for which binomial distribution is always zero. The reset resets the distribution so that the coming uses of the object do not depend on values that are already produced by it.

#include <bits/stdc++.h>
#include <chrono>
#include <random>
typedef long long ll;
using namespace std;
int main()
{
    unsigned seed = chrono::system_clock::now().time_since_epoch().count();
    default_random_engine generator(seed); // generator engine from a time-based seed

    binomial_distribution<int> distribution(10, 0.4); // Initialising the binomial distribution

    cout << "The distribution (k=10, p=0.4): ";
    for (int i = 0; i < 10; ++i)
    {
        cout << distribution(generator) << " "; // The operator function
    }
    cout << endl;
    return 0;
}

The output is:

The distribution (k=10, p=0.4): 6 3 9 5 8 5 6 6 5 8
#include <bits/stdc++.h>
#include <chrono>
#include <random>
typedef long long ll;
using namespace std;
int main()
{
    unsigned seed = chrono::system_clock::now().time_since_epoch().count();
    default_random_engine generator(seed); // generator engine from a time-based seed

    binomial_distribution<int> distribution(10, 0.4); // Initialising the binomial distribution

    // First random number is generated
    cout << distribution(generator) << endl;

    //Resets the distribution
    distribution.reset();

    // Second random number is
    //generated independent of previous number
    cout << distribution(generator) << endl;

    return 0;
}

The output is:

6
3

The point to note here is that the output of the codes above is random so it may not match with the above-written output.

You may also like to learn:

Leave a Reply

Your email address will not be published. Required fields are marked *