Continuous Uniform Distribution with Python
The Continuous Uniform Distribution is a probability distribution where any value within a specified range has an equal probability of occurring. This uniformity implies that every subinterval within the specified range has an equal likelihood of containing the observed value.
In this tutorial, we embark on a journey by elucidating the distinctions between Continuous and Discrete Uniform Distribution. Following that, we delve into the mathematical formulations of Probability Density Function (PDF) and Cumulative Distribution Function (CDF), exploring their interconnection. Subsequently, we immerse ourselves in a practical example involving bus delay times, where we visualise the uniformity of the dataset, calculate, and visualize the CDF for both at most and at least values of x.
1. Continuous Uniform Distribution vs Discrete Uniform Distribution
Before delving into the topic, let’s distinguish between Continuous Uniform Distribution and Discrete Uniform Distribution.
The Continuous Uniform Distribution allows for any real number within a range, with a constant probability density and zero probability at specific points. In contrast, the Discrete Uniform Distribution deals with distinct integers within a range, assigning equal probabilities to individual points through a probability mass function where the probability at each point is greater than zero. The key distinction lies in the nature of values and how probabilities are assigned within the specified range.
In the discrete case of this example, the possible values range from 1 to 6. When rolling a die, you can obtain whole numbers such as 2 or 3; there are no values in between. We cannot roll a die and obtain a value of 2.37. This discrete nature is a defining characteristic.
In the bus delay scenario, we assumed minimum and maximum delays to be 1 and 6 minutes, respectively. However, bus delays can be continuous, encompassing values like 3 minutes and 23 seconds or 4.453632 minutes. Consequently, there exists a continuous spectrum of possible delay values.
2. Probability Density Function (PDF) and Cumulative Distribution Function (CDF)
Probability Density Function (PDF) of a Continuous Uniform Distribution, denoted as f(x), is defined as:
where a is the minimum value in the range, b is the maximum value, and b>a.
This function ensures a constant probability density throughout the entire specified interval.
In the continuous case, the probability for any specific point is technically zero. Instead, we consider the probability of an interval. The total area under the probability density function over the entire range represents the cumulative probability and must equal 1. When you integrate this function [1] over the entire range, the total area under the curve is 1:
Cumulative Distribution Function (CDF) denoted as F(x), provides the probability that a random variable takes a value less than or equal to x.
for a≤x≤b,
and F(x)=0 for x<a
and F(x)=1 for x>b. The CDF increases linearly within the interval, reflecting the cumulative probability of observing values up to x.
The F(x) is obtained by integrating the PDF —f(t)(here, f(t) represents the probability density function (PDF) with respect to t to avoid confusion with the specific value x from the interval.) from the minimum value a up to x i.e. any specified vale from the interval, for example bus delay for 2.32 minutes:
Substituting x with 2.32 in the CDF formul: F(2.32)=(2.32−1)/(6−1)=0.264.
If x is equal to b — the maximum value of the range, then F(x) equals 1.
3. Practical examples for Continuous Uniform Distribution with Python
Now, let’s delve into a practical example — considering the scenario of bus delay times. Assume a minimum delay time of 1 minute and a maximum delay time of 5 minutes. We’ll visualise the data through a plot to examine its uniformity.
Get Ja X’s stories in your inbox
Join Medium for free to get updates from this writer.
Initially, we must import the required libraries and establish a connection to Google Drive to facilitate the importation of files from it.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
import scipy.stats as stats
# this library contains a large number of probability distributions
# as well as a growing library of statistical functions
# connecting to the gooogle drive
from google.colab import drive
drive.mount('/content/drive')bus_delay = pd.read_csv("/content/drive/path/to_your_file/bus_delay.csv")
bus_delay.head()Now, let’s visualize the entire dataset to validate its uniform distribution.
plt.figure(figsize=(10, 6))
# Plot the histogram for Delay Time column in bus_delay csv
sns.histplot(bus_delay["Delay Time"], kde=False, color='darkgreen', stat='density', linewidth=0)
# Adding a horizontal line at y=1/4 (25% probability)
plt.axhline(1 / 4, color="red", linestyle='--', linewidth=2)
# Remove left and bottom spines to eliminate the box just for better visual
sns.despine(left=True, bottom=True)
# Set labels and title
plt.xlabel("Bus delay in minutes", fontsize=14, color='darkgreen')
plt.ylabel("Density", fontsize=14, color='darkgreen')
plt.title("Data Distribution", fontsize=18, color='darkgreen')
# Set the color of tick labels on both axes
plt.xticks(color='orange')
plt.yticks(color='orange')
# Display the plot
plt.show()Graphical representation of Uniform Distribution would appear as a flat, constant line, indicating that each value has the same chance of being observed. Looking at our graph, it’s evident that it doesn’t precisely form a rectangle. However, we can still consider it as uniform & suitable for analysis and further work.
Now, we will compute the Cumulative Distribution Function (CDF) and Probability Density Function (PDF) using the uniform.cdf and uniform.pdf functions, respectively.
from scipy.stats import uniform
# Define the parameters of the uniform distribution
a = 1 # Lower bound
b = 5 # Upper bound
# Calculate the CDF & PDF for x=2.32
x = 2.32
cdf_value = uniform.cdf(x, loc=a, scale=(b-a))
pdf_value = uniform.pdf(x, loc=a, scale=(b-a))
# Print the results
print(f"The CDF for x={x} in the uniform distribution is: {cdf_value}")
print(f"The PDF in the uniform distribution is: {pdf_value}")The CDF for x=2.32 in the uniform distribution is: 0.32999999999999996
The PDF in the uniform distribution is: 0.25Now, let’s plot the CDF for the value 2.32.
plt.figure(figsize=(10, 6))
# extracting Delay Time column
delay_data = bus_delay["Delay Time"]
highlight_value = 2.32
# Create bins and assigning histogram values
hist_values, bin_edges = np.histogram(delay_data, bins=30, density=True)
# Plot histogram bars & color respective bars
for edge, value in zip(bin_edges[:-1], hist_values):
if edge <= highlight_value:
color = '#FF6666' #red
else:
color = '#009900' #green
plt.bar(edge, value, width=np.diff(bin_edges)[0], color=color, alpha=1, align='edge', edgecolor='none')
# Highlight the value 2.32 with a red dashed line
plt.axvline(highlight_value, color='red', linestyle='--', linewidth=2)
# Add a horizontal line at y=1/4 (25% probability)
plt.axhline(1 / 4, color="red", linestyle='--', linewidth=2)
#Add 2.32 label on X axis to indicate x value
plt.text(highlight_value, 0, str(highlight_value), color='red', ha='center', va='top', fontsize=10)
# Add a text annotation for CDF value at x ≤ 2.32
plt.text(highlight_value, 0.05, "≈ CDF = 0.33", color='orange', ha='left', va='bottom', fontsize=12, rotation='vertical')
# Remove left and bottom spines to eliminate the box just for better visual
sns.despine(left=True, bottom=True)
# Set labels and title
plt.xlabel("Bus delay in minutes", fontsize=14, color='darkgreen')
plt.ylabel("Density", fontsize=14, color='darkgreen')
plt.title("CDF for x≤2.32", fontsize=18, color='#FF6666')
# Set the color of tick labels on both axes
plt.xticks(color='orange')
plt.yticks(color='orange')
# Display the plot
plt.show()It indicates that there is a probability of around 33% that a randomly chosen bus will experience a delay of at most 2.32 minutes.
You may inquire about the probability of a randomly chosen bus experiencing a delay of at least any given minutes.
So, to find the probability for example the delay is at least for 3.1 minutes, you can use: P(X≥ 3.1)=1−P(X< 3.1) :
Now, we can visually represent it, where the red region corresponds to P(X≥3.1).
plt.figure(figsize=(10, 6))
# extracting Delay Time column
delay_data = bus_delay["Delay Time"]
highlight_value = 3.1
# Create bins and assigning histogram values
hist_values, bin_edges = np.histogram(delay_data, bins=55, density=True)
# Plot histogram bars
for edge, value in zip(bin_edges[:-1], hist_values):
if edge <= highlight_value:
color = '#009900' # green
else:
color = '#FF6666' # red
plt.bar(edge, value, width=np.diff(bin_edges)[0], color=color, alpha=1, align='edge', edgecolor='none')
# Highlight the value 3.1 with a red dashed line
plt.axvline(highlight_value, color='red', linestyle='--', linewidth=2)
# Add a horizontal line at y=1/4 (25% probability)
plt.axhline(1 / 4, color="red", linestyle='--', linewidth=2)
# Add a text annotation for x value on x axis
plt.text(highlight_value, 0, str(highlight_value), color='red', ha='center', va='top', fontsize=10)
# Add a text annotation for CDF value at x <= 3.1
plt.text(highlight_value, 0.05, "≈ CDF = 0.475", color='orange', ha='left', va='bottom', fontsize=12, rotation='vertical')
# Remove left and bottom spines to eliminate the box
sns.despine(left=True, bottom=True)
# Set labels and title
plt.xlabel("Bus delay in minutes", fontsize=14, color='darkgreen')
plt.ylabel("Density", fontsize=14, color='darkgreen')
plt.title("CDF for x≥3.1", fontsize=18, color='red')
# Set the color of tick labels on both axes
plt.xticks(color='orange')
plt.yticks(color='orange')
# Display the plot
plt.show()We can infer that the probability of a randomly selected bus experiencing a delay of at least 3.1 minutes is 47.5%, illustrated by the highlighted red area.










