Uniform Distribution

🎲 Uniform Distribution in Python

The Uniform Distribution generates random numbers that are equally likely to occur within a specified range.

It is widely used in simulations, random sampling, and scenarios where every outcome is equally probable.


✅ 1. Characteristics of Uniform Distribution

  • Continuous or discrete (NumPy supports continuous by default)

  • Parameters:

    • low → minimum value

    • high → maximum value

    • size → number of random samples

  • All values between low and high have equal probability


✅ 2. Generate Uniform Data Using NumPy

import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

# Generate 1000 uniform random numbers between 0 and 10
data = np.random.uniform(low=0.0, high=10.0, size=1000)

print(data[:10]) # print first 10 values

Output (example):

[1.23, 7.45, 3.67, 0.89, 9.12, 4.56, 2.78, 6.12, 8.90, 5.34]

✅ 3. Visualize Uniform Distribution

sns.histplot(data, bins=20, kde=True, color='skyblue')
plt.title("Uniform Distribution")
plt.xlabel("Value")
plt.ylabel("Frequency")
plt.show()
  • Histogram appears flat

  • kde=True adds smooth density curve


✅ 4. Change Range and Size

# Uniform distribution between -5 and 5
data2 = np.random.uniform(low=-5, high=5, size=500)

sns.histplot(data2, bins=20, kde=True, color='orange')
plt.title("Uniform Distribution (-5 to 5)")
plt.show()


✅ 5. Generate 2D Uniform Array

arr = np.random.uniform(low=0, high=1, size=(3, 4))
print(arr)

Output (example):

[[0.12 0.56 0.34 0.78]
[0.45 0.23 0.89 0.67]
[0.34 0.12 0.90 0.11]]


🧠 Summary Table

Function Parameters Description
np.random.uniform() low, high, size Generates continuous uniform random numbers
Continuous low=0, high=1 Default random floats between 0 and 1
2D array size=(rows, cols) Generates matrix of random numbers

🎯 Practice Exercises

  1. Generate 1000 numbers uniformly between 50–100 and plot histogram.

  2. Generate 5×5 matrix of uniform random numbers between 0–1.

  3. Create uniform data between -10 and 10 and compute mean and standard deviation.

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *