Open In App

Binomial Distribution in NumPy

Last Updated : 23 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The Binomial Distribution is a fundamental concept in probability and statistics. It models the number of successes in a fixed number of independent trials where each trial has only two possible outcomes: success or failure. This distribution is widely used in scenarios like coin flips, quality control and surveys. The numpy.random.binomial() method generates random numbers that follow a Binomial Distribution. It has three key parameters:

  • n : The number of trials (e.g., number of coin flips).
  • p : The probability of success in each trial (e.g., probability of getting heads in a coin flip).
  • size : The shape of the returned array.

Syntax:

numpy.random.binomial(n, p, size=None)

Example 1: Generate a Single Random Number

To generate a single random number from a Binomial Distribution with n=10 trials and p=0.5 probability of success:

Python
import numpy as np

random_number = np.random.binomial(n=10, p=0.5)
print(random_number)

Output:

3

Example 2: Generate an Array of Random Numbers

To generate multiple random numbers:

Python
random_numbers = np.random.binomial(n=10, p=0.5, size=5)
print(random_numbers)

Output:

[6 5 4 3 5]

Visualizing the Binomial Distribution

Visualizing the generated numbers helps in understanding their behavior. Below is an example of plotting a histogram of random numbers generated using numpy.random.binomial.

Python
import numpy as np
import matplotlib.pyplot as plt

n = 10  
p = 0.5  
size = 1000  

data = np.random.binomial(n=n, p=p, size=size)

plt.hist(data, bins=np.arange(-0.5, n+1.5, 1), density=True, edgecolor='black', alpha=0.7, label='Histogram')

x = np.arange(0, n+1)  
pmf = binom.pmf(x, n=n, p=p)  
plt.scatter(x, pmf, color='red', label='Theoretical PMF')
plt.vlines(x, 0, pmf, colors='red', linestyles='dashed')  

plt.title("Binomial Distribution (n=10, p=0.5)")
plt.xlabel("Number of Successes")
plt.ylabel("Probability")
plt.legend()
plt.grid(True)

plt.show()

Output:

Binomial-Distribution
Binomial Distribution

The image shows a Binomial Distribution with 10 trials (n=10) and a 50% success rate (p=0.5). The blue bars represent simulated data and the red dots show the expected probabilities. The distribution is symmetric, centered around 5 successes.


Next Article
Article Tags :
Practice Tags :

Similar Reads