0
0
SciPydata~5 mins

Uniform distribution in SciPy

Choose your learning style9 modes available
Introduction

The uniform distribution helps us understand situations where all outcomes are equally likely. It is useful to model random events with no bias.

When simulating rolling a fair die where each face has the same chance.
When picking a random number between two limits with equal chance.
When modeling equal probability of events in a simple game.
When generating random samples for testing algorithms.
When estimating probabilities in simple random experiments.
Syntax
SciPy
from scipy.stats import uniform

# Create a uniform distribution object
rv = uniform(loc=lower_bound, scale=upper_bound - lower_bound)

# Get probability density function (PDF) at x
pdf_value = rv.pdf(x)

# Get cumulative distribution function (CDF) at x
cdf_value = rv.cdf(x)

# Generate random samples
samples = rv.rvs(size=number_of_samples)

loc sets the start (minimum) of the distribution.

scale sets the width (max - min) of the distribution.

Examples
Creates a uniform distribution from 0 to 1 and finds the PDF at 0.5.
SciPy
from scipy.stats import uniform

rv = uniform(loc=0, scale=1)  # Uniform between 0 and 1
print(rv.pdf(0.5))
Creates a uniform distribution from 10 to 15 and finds the CDF at 12.
SciPy
rv = uniform(loc=10, scale=5)  # Uniform between 10 and 15
print(rv.cdf(12))
Generates 4 random samples between 5 and 8.
SciPy
samples = uniform(loc=5, scale=3).rvs(size=4)
print(samples)
Sample Program

This program creates a uniform distribution between 2 and 7. It calculates and prints the PDF and CDF at 3, generates 5 random samples, and plots the PDF and CDF curves.

SciPy
from scipy.stats import uniform
import numpy as np
import matplotlib.pyplot as plt

# Define uniform distribution from 2 to 7
start = 2
end = 7
rv = uniform(loc=start, scale=end - start)

# Calculate PDF values for points between 0 and 10
x = np.linspace(0, 10, 100)
pdf_values = rv.pdf(x)

# Calculate CDF values
cdf_values = rv.cdf(x)

# Generate 5 random samples
samples = rv.rvs(size=5)

# Print results
print(f"PDF at 3: {rv.pdf(3):.3f}")
print(f"CDF at 3: {rv.cdf(3):.3f}")
print(f"Random samples: {samples}")

# Plot PDF and CDF
plt.plot(x, pdf_values, label='PDF')
plt.plot(x, cdf_values, label='CDF')
plt.title('Uniform Distribution from 2 to 7')
plt.xlabel('x')
plt.ylabel('Probability')
plt.legend()
plt.grid(True)
plt.show()
OutputSuccess
Important Notes

The PDF value for uniform distribution is constant between loc and loc+scale.

Values outside the range have PDF = 0 and CDF = 0 or 1 depending on side.

Random samples follow the uniform distribution within the specified range.

Summary

Uniform distribution models equal chance outcomes between two limits.

Use scipy.stats.uniform with loc and scale to set range.

PDF is constant inside the range; CDF increases linearly.