How to model the uniform distribution in Python

Overview

A uniform distribution is a probability distribution where every event has an equal likelihood or chance of happening.

Its probability density function is as shown below:

f(x)f(x) == 1ba\frac{1}{b-a} when xx is b\le b and a\ge a and 00 if x>bx>b or x<ax<a .

When a value or variable XX follows a uniform distribution, the probability of an event (E)(E) occurring is shown by

p(x)=1Np(x) =\frac1N, where N is the number of events likely to occur.

Practical applications of the uniform distribution

Uniform distribution is applicable where the likelihood of an event occurring is the same all through, such as when you roll a die one time, the probability that it falls on a number between 1 and 6 follows a uniform distribution because each number is equally likely to occur.

For example, there are 6 possible numbers the die can land on, so the probability that you roll a 1 is 1/6, the probability that you roll a 2 is 1/6, and so on.

Code implementation in Python

There are 2 ways to model a uniform distribution in python.

1. Using the NumPy library in Python.

import numpy as np
import matplotlib.pyplot as plt
values = np.random.uniform(0.01, 0.99, 1000)
count, bins, ignored = plt.hist(values, 20, density=True)
plt.plot(bins, np.ones_like(bins),color='r')
plt.title('Uniform Distribution')
plt.ylabel('Density')
plt.xlabel('Values')
plt.show()

Explanation

The above code uses NumPy to generate 1,000 random points of a uniform distribution ranging from 0.01 to 0.99 and then visualizes the dataset using a histogram.

The pdf of each point is therefore approximately 1(0.990.01)=1\frac{1}{(0.99-0.01)} = { 1}

2. Using the SciPy library in Python

from scipy.stats import uniform
import matplotlib.pyplot as plt
import numpy as np
x = uniform.rvs(0.01,0.99,size=1000)
print(f'pdf of x is {uniform.pdf(x[0])}')
plt.hist(x,density = True)
plt.axhline(y=uniform.pdf(x[0]),color='r')
plt.title('Uniform distribution')
plt.ylabel('Density')
plt.xlabel('X')
plt.show()

Explanation

The code above uses Scipy’s uniform method to generate random variables of a uniform distribution and then uses the histogram to display them.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved