Mathew K Analytics

Lesson 11 · Probability and Statistics in python

Understanding Continuous Probability Distributions: Uniform, Normal, and Exponential Explained

We will load a dataset and preview it. Welcome! Today we will explore three very important continuous probability distributions. You will see how to create,…

⬇ Download notebookOpen in Colab ↗

📓 Full notebook

Download .ipynb

Data setup (Tips Dataset)#

We will load a dataset and preview it.

import seaborn as sns
import matplotlib.pyplot as plt
df = sns.load_dataset('tips')
print(df.shape)
print(df.head(3))
sns.violinplot(data=df, x='day', y='total_bill', hue='sex', split=True); plt.show()
(244, 7)
   total_bill   tip     sex smoker  day    time  size
0       16.99  1.01  Female     No  Sun  Dinner     2
1       10.34  1.66    Male     No  Sun  Dinner     3
2       21.01  3.50    Male     No  Sun  Dinner     3
No description has been provided for this image

Continuous Distributions: Uniform, Normal, and Exponential#

Welcome! Today we will explore three very important continuous probability distributions.

You will see how to create, visualize, and use these distributions in Python.

Let us unlock some mathematical magic that helps explain everyday randomness.

# Data setup
import warnings; warnings.filterwarnings('ignore')
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

# For data preview later
sns.set(style='whitegrid')

What Are Continuous Distributions?#

A continuous distribution tells us the chance of many values, not just a few.

For example, a persons height or the waiting time between buses.

Three famous examples are Uniform, Normal, and Exponential.

We will see each one with code and real-life connections.

# Uniform Distribution - Simulating Random Decimal Numbers
uniform_data = np.random.uniform(0, 10, 1000)

plt.figure(figsize=(7,4))
sns.histplot(uniform_data, bins=20, kde=True, color='skyblue')
plt.title('Uniform Distribution (0 to 10)')
plt.xlabel('Value')
plt.ylabel('Frequency')
plt.show()
No description has been provided for this image
# Uniform Distribution: Everyday Example
from scipy.stats import uniform

prob = uniform.cdf(3, loc=0, scale=10)
print(f"Probability that X < 3 when X is uniform between 0 and 10: {prob:.2f}")
Probability that X < 3 when X is uniform between 0 and 10: 0.30

Normal Distribution: The Bell Curve#

This is a superstar in statistics.

Most people's heights, exam scores, and many measurements follow a normal or bell curve shape.

Let us see it with numbers and graphs.

# Simulating Heights Using Normal Distribution
heights = np.random.normal(loc=170, scale=10, size=1000)

plt.figure(figsize=(7,4))
sns.histplot(heights, bins=30, kde=True, color='orchid')
plt.title('Simulated Heights (Normal Distribution, mean=170, sd=10)')
plt.xlabel('Height (cm)')
plt.ylabel('Number of People')
plt.show()
No description has been provided for this image
# Normal Probability Example
from scipy.stats import norm

prob_180 = norm.cdf(180, loc=170, scale=10)
print("Probability that height is less than 180 cm:", round(prob_180, 3))

prob_190 = norm.cdf(190, loc=170, scale=10)
print("Probability that height is less than 190 cm:", round(prob_190, 3))
Probability that height is less than 180 cm: 0.841
Probability that height is less than 190 cm: 0.977
# Visualizing Normal Distribution with Mean and Spread
x = np.linspace(140, 200, 500)
for mu, sigma, color in [(170, 10, 'orchid'), (170, 20, 'deepskyblue'), (180, 10, 'coral')]:
    y = norm.pdf(x, mu, sigma)
    plt.plot(x, y, label=f"mean={mu}, sd={sigma}", color=color)

plt.title('Normal Distribution: Changing Mean and SD')
plt.xlabel('Value')
plt.ylabel('Probability')
plt.legend()
plt.show()
No description has been provided for this image

Exponential Distribution: Waiting Times#

Families often use this when studying how long you must wait between rare events.

For example, the time between buses arriving at a station, or how quickly emails arrive.

Let us look at an example and visualize it.

# Exponential Distribution - Simulate Waiting Times
wait_times = np.random.exponential(scale=5, size=1000)

plt.figure(figsize=(7,4))
sns.histplot(wait_times, bins=30, kde=True, color='limegreen')
plt.title('Exponential Distribution (mean waiting time = 5)')
plt.xlabel('Waiting Time (minutes)')
plt.ylabel('Frequency')
plt.show()
No description has been provided for this image
# Probability of Waiting Less Than 3 Minutes
from scipy.stats import expon

prob_less_3 = expon.cdf(3, scale=5)
print("Probability wait is less than 3 minutes:", round(prob_less_3, 3))

prob_more_10 = 1 - expon.cdf(10, scale=5)
print("Probability wait is over 10 minutes:", round(prob_more_10, 3))
Probability wait is less than 3 minutes: 0.451
Probability wait is over 10 minutes: 0.135
# Comparing Distributions on One Plot
x = np.linspace(0, 20, 500)
plt.figure(figsize=(8,5))
plt.plot(x, uniform.pdf(x, loc=0, scale=10), label='Uniform(0,10)', color='deepskyblue')
plt.plot(x, norm.pdf(x, loc=10, scale=3), label='Normal(mean=10, sd=3)', color='orchid')
plt.plot(x, expon.pdf(x, scale=5), label='Exponential(mean=5)', color='limegreen')
plt.title('Uniform vs Normal vs Exponential Distributions')
plt.xlabel('Value')
plt.ylabel('Probability')
plt.legend()
plt.show()
No description has been provided for this image

Loading Real Data: Simulated Arrival Times#

Let us try working with real data. Imagine we tracked customer arrivals at a shop every minute for an hour.

We will make sample data to practice!

# Simulate Customer Arrivals (like exponential process)
np.random.seed(42)
arrivals = np.random.exponential(scale=5, size=60)
arrival_times = np.cumsum(arrivals)
df = pd.DataFrame({'Minutes': np.arange(1, 61), 'Time_of_Arrival': arrival_times})
df['Time_of_Arrival'] = df['Time_of_Arrival'].round(2)
print(df.head())
   Minutes  Time_of_Arrival
0        1             2.35
1        2            17.40
2        3            23.98
3        4            28.55
4        5            29.39
# Plotting Arrival Pattern
plt.figure(figsize=(8,4))
plt.plot(df['Minutes'], df['Time_of_Arrival'], marker='o', color='purple')
plt.title('Cumulative Arrival Times Over One Hour')
plt.xlabel('Minute')
plt.ylabel('Arrival Time (minutes)')
plt.show()
No description has been provided for this image
# Practice: Predict the Next Arrival
next_minute = int(input("Guess the minute the next customer arrives after minute 60: "))
if next_minute > 60 and next_minute < 80:
    print("Great guess! That is within a realistic range for this shop.")
else:
    print("Interesting guess! Keep an eye on how exponential randomness works.")
    
Great guess! That is within a realistic range for this shop.
# Challenge: Which Distribution Should I Use?
scenario = input("You are asked to model the height of a random person. Which distribution fits best? (uniform, normal, exponential): ")
if scenario.lower() == 'normal':
    print("Correct! People\'s heights usually follow a normal curve.")
else:
    print("Try again. Think of shapes like bell curves versus even or waiting time.")
    
Correct! People's heights usually follow a normal curve.
# Best Practices: Choosing a Distribution

# - Uniform: Any value in a range is equally likely (e.g., random PIN).
# - Normal: Values bunch up near average, fewer outliers (e.g., heights).
# - Exponential: Chance drops off over time, no true maximum (e.g., waiting times).

# When unsure, draw a histogram of your data first!

Quick Review: What Did We Learn?#

  • Uniform: All values are equally likely in a range.
  • Normal: Most values cluster near the center, forming a bell shape.
  • Exponential: Models the time between rare events.

You practiced with data, visualized shapes, and even made predictions!

Try using these ideas on data from everyday life.

Want More Data Adventures?#

If you learned something new, please like, comment your favorite fact, and subscribe to the YouTube channel.

There are many more hands-on Python lessons coming soon. Keep practicing, and see you in the next video!

Found this useful?

All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.