A Uniform Distribution is used when all the numbers in a range have the same chance of being picked.For example, if we choose a number between 10 and 20 and every number in that range is just as likely as any other. In Python's NumPy library you can generate random numbers following a Uniform Distribution using the numpy.random.uniform()
method. The syntax is:
Syntax: numpy.random.uniform(low=0.0, high=1.0, size=None)
- low : The lower bound of the range (inclusive). Default is
0.0
. - high : The upper bound of the range (exclusive). Default is
1.0
. - size : The shape of the returned array.
Example 1: Generate a Single Random Number
In this example we can see how to generate a single random number from a default Uniform Distribution (low=0
, high=1
):
Pythonimportnumpyasnprandom_number=np.random.uniform()print(random_number)
Output:
0.1466964230422637
To generate multiple random numbers:
Pythonrandom_numbers=np.random.uniform(size=5)print(random_numbers)
Output:
[0.72798597 0.35286575 0.10228773 0.56598948 0.03552713]
Visualizing the Uniform Distribution
Visualizing the generated numbers helps in understanding their behavior. Let's see a example to plot a histogram of random numbers using numpy.random.uniform
function.
Pythonimportnumpyasnpimportmatplotlib.pyplotaspltimportseabornassnslow=10high=20size=1000data=np.random.uniform(low=low,high=high,size=size)sns.histplot(data,bins=30,kde=False,color='skyblue',edgecolor='black')plt.title(f"Uniform Distribution (Range:{low} to{high})")plt.xlabel("Value")plt.ylabel("Frequency")plt.grid(True)plt.show()
Output:
Uniform DistributionThe image above shows aUniform Distribution between 10 and 20. This means every number in that range is equally likely to happen. The bars in the histogram show that the values from 10 to 20 appear about the same number of times.