Python - Binomial Distribution
Last Updated :
16 Jul, 2020
Binomial distribution is a probability distribution that summarises the likelihood that a variable will take one of two independent values under a given set of parameters. The distribution is obtained by performing a number of
Bernoulli trials.
A Bernoulli trial is assumed to meet each of these criteria :
- There must be only 2 possible outcomes.
- Each outcome has a fixed probability of occurring. A success has the probability of p, and a failure has the probability of 1 - p.
- Each trial is completely independent of all others.
The binomial random variable represents the number of successes(
r) in
n successive independent trials of a Bernoulli experiment.
Probability of achieving
r success and
n-r failure is :
p^r * (1-p)^{n-r}
The number of ways we can achieve
r successes is :
\frac{n!}{(n-r)!\ *\ r!}
Hence, the
probability mass function(pmf), which is the total probability of achieving
r success and
n-r failure is :
\frac{n!}{(n-r)!\ *\ r!}\ *\ p^r * (1-p)^{n-r}
An example illustrating the distribution :
Consider a random experiment of tossing a biased coin
6 times where the probability of getting a head is
0.6. If 'getting a head' is considered as '
success' then, the binomial distribution table will contain the probability of
r successes for each possible value of r.
r | 0 | 1 | 2 | 3 | 4 | 5 | 6 |
P(r) | 0.004096 | 0.036864 | 0.138240 | 0.276480 | 0.311040 | 0.186624 | 0.046656 |
This distribution has a mean equal to
np and a variance of
np(1-p).
Using Python to obtain the distribution :
Now, we will use Python to analyse the distribution(using
SciPy) and plot the graph(using
Matplotlib).
Modules required :
- SciPy:
SciPy is an Open Source Python library, used in mathematics, engineering, scientific and technical computing.
Installation :
pip install scipy
- Matplotlib:
Matplotlib is a comprehensive Python library for plotting static and interactive graphs and visualisations.
Installation :
pip install matplotlib
The
scipy.stats module contains various functions for statistical calculations and tests. The
stats() function of the
scipy.stats.binom module can be used to calculate a binomial distribution using the values of
n and
p.
Syntax : scipy.stats.binom.stats(n, p)
It returns a tuple containing the mean and variance of the distribution in that order.
scipy.stats.binom.pmf() function is used to obtain the probability mass function for a certain value of r, n and p. We can obtain the distribution by passing all possible values of r(0 to n).
Syntax : scipy.stats.binom.pmf(r, n, p)
Calculating distribution table :
Approach :
- Define n and p.
- Define a list of values of r from 0 to n.
- Get mean and variance.
- For each r, calculate the pmf and store in a list.
Code :
python3
from scipy.stats import binom
# setting the values
# of n and p
n = 6
p = 0.6
# defining the list of r values
r_values = list(range(n + 1))
# obtaining the mean and variance
mean, var = binom.stats(n, p)
# list of pmf values
dist = [binom.pmf(r, n, p) for r in r_values ]
# printing the table
print("r\tp(r)")
for i in range(n + 1):
print(str(r_values[i]) + "\t" + str(dist[i]))
# printing mean and variance
print("mean = "+str(mean))
print("variance = "+str(var))
Output :
r p(r)
0 0.004096000000000002
1 0.03686400000000005
2 0.13824000000000003
3 0.2764800000000001
4 0.31104
5 0.18662400000000007
6 0.04665599999999999
mean = 3.5999999999999996
variance = 1.44
Code: Plotting the graph using matplotlib.pyplot.bar() function to plot vertical bars.
python3
from scipy.stats import binom
import matplotlib.pyplot as plt
# setting the values
# of n and p
n = 6
p = 0.6
# defining list of r values
r_values = list(range(n + 1))
# list of pmf values
dist = [binom.pmf(r, n, p) for r in r_values ]
# plotting the graph
plt.bar(r_values, dist)
plt.show()
Output :

When success and failure are equally likely, the binomial distribution is a
normal distribution. Hence, changing the value of
p to
0.5, we obtain this graph, which is identical to a normal distribution plot :
Similar Reads
Python Tutorial | Learn Python Programming Language Python Tutorial â Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly.Python is:A high-level language, used in web development, data science, automatio
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Enumerate() in Python enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Input and Output in Python Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is
8 min read