Python

Generating Random Numbers with Uniform Distribution in Python

In this post, we will learn about generating uniform random numbers in python. All events have an equal chance of occurring; hence, the probability density is uniform. The density function of uniform distribution is:

p(x) =  1/(b-a), a <x <b .

For x outside the interval (a, b) the probability of the event is 0. To generate random numbers from a uniform distribution, we can use NumPy’s numpy.random.uniform method. Let’s see a simple example:

$ python3

Python 3.8.5 (default, Mar  8 2021, 13:02:45)

[GCC 9.3.0] on linux2

Type “help”, “copyright”, “credits” or “license” for more information.

>>> import numpy as np

>>> np.random.uniform()

0.7496272782328547

The above code generated a uniform random number sampled between 0 and 1. We can specify the lower boundary of the interval and the upper boundary of the interval using the parameters low and high. The parameter low specifies the lower boundary of the interval, and by default, it takes a value of 0. The parameter high specifies the upper boundary of the interval, and by default, it takes a value of 1.

>>> np.random.uniform(low=0, high=10)

5.7355211819715715

Let’s say we want to create an array of values. We can specify the size of the array using the parameter size. It takes either an integer or a tuple of integers as arguments and produces random samples of the specified size.

>>> np.random.uniform(0, 10, size=4)

array([6.78922668, 5.07844106, 6.4897771 , 1.51750403])

>>> np.random.uniform(0, 10, size=(2, 2))

array([[3.61202254, 8.3065906 ],

           [0.59213768, 2.16857342]])

In the above example, passing (2, 2) as size created an array of random numbers of size (2, 2).

Random numbers generated by a distribution can be visualized to see their distribution. In this part, we will be using the library seaborn for visualizing random numbers.

>>> import seaborn as sns

>>> import matplotlib.pyplot as plt

>>> a = np.random.uniform(0, 10, 10000)

>>> sns.histplot(a)

<AxesSubplot:ylabel='Count'>

>>> plt.show()

The above-generated histogram plot represents a distribution by counting the number of observations that fall within each discrete bin. We observe that the number of samples in each discrete bin is uniform for random numbers generated by a uniform distribution. We also note that no counts are observed for elements outside of the interval (0, 10). Hence, the probability for an element less than the lower interval or higher than the lower interval is 0, and within the interval, the probability of a random sample is 1 / (10 – 0) = 0.1.

About the author

Arun Palaniappan