How to Make a Bell Curve in Python

The normal distribution, also known as the Gaussian distribution, is a continuous probability distribution characterized by its bell-shaped curve. This distribution is widely used in statistics and mathematics due to its numerous applications, such as modeling errors, measuring IQ scores, and analyzing financial data. In this article, we will discuss the mathematical concept of the normal distribution and show you how to create a bell curve using Python.

Mathematical Background

The normal distribution is defined by the following probability density function (PDF):

 \displaystyle f(x) = \frac{1}{\sqrt{2\pi}\sigma}e^{-\frac{(x-\mu)^2}{2\sigma^2}}

where:

  • \mu is the mean (average value) of the distribution.
  • \sigma is the standard deviation (a measure of the spread of the distribution).
  • x is any value in the distribution.

Creating a Bell Curve in Python

To create a bell curve in Python, we will use the NumPy library, which provides an implementation of the normal distribution.

Method 1: Using the scipy.stats.norm.pdf function

First, we will create a bell curve by computing the probability density function (PDF) for a given set of values and plotting the results:

import numpy as np
import matplotlib.pyplot as plt

# Set the mean and standard deviation
mean = 0
std_dev = 1

# Generate a range of x values
x = np.linspace(-5, 5, 1000)

# Compute the PDF for each x value
pdf = np.exp(-np.power(x - mean, 2) / (2 * np.power(std_dev, 2))) / np.sqrt(2 * np.pi * np.power(std_dev, 2))

# Plot the bell curve
plt.plot(x, pdf, 'b')
plt.xlabel('x')
plt.ylabel('PDF')
plt.title('Bell Curve using scipy.stats.norm.pdf')
plt.show()

Method 2: Using the scipy.stats.norm.rvs function

Another way to create a bell curve in Python is by generating random samples from the normal distribution and plotting the results:

import numpy as np
import matplotlib.pyplot as plt

# Generate 10,000 random samples from the normal distribution
samples = np.random.normal(mean, std_dev, size=(10000,))

# Plot a histogram of the samples
plt.hist(samples, bins=50, density=True, alpha=0.5)
plt.xlabel('x')
plt.ylabel('Density')
plt.title('Bell Curve using scipy.stats.norm.rvs')
plt.show()

Leave a Reply

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