Random Numbers in NumPy

🎲 Random Numbers in NumPy (Complete Guide)

NumPy provides a powerful random module (numpy.random) to generate random numbers, arrays, choices, and distributions.


✅ 1. Generate a Single Random Number

from numpy import random

num = random.rand()
print(num)

👉 Generates a random float between 0 and 1.


✅ 2. Generate Random Integer

num = random.randint(10)
print(num)

👉 Generates a random integer between 0 and 9.


With Range:

num = random.randint(5, 20)
print(num)

✅ 3. Generate Random Array

1D Array

arr = random.randint(10, size=5)
print(arr)

2D Array

arr = random.randint(10, size=(3, 4))
print(arr)

✅ 4. Generate Random Float Array

arr = random.rand(3, 2)
print(arr)

👉 Returns random floats between 0 and 1.


🎯 Random Choice (Pick Random Value from List)

arr = random.choice([3, 5, 7, 9])
print(arr)

Multiple Random Choices

arr = random.choice([3, 5, 7, 9], size=5)
print(arr)

🔄 Random Choice with Output Shape

arr = random.choice([1, 2, 3, 4], size=(3, 3))
print(arr)

🎯 Random Distribution

NumPy supports many probability distributions.

Example: Normal Distribution

arr = random.normal(loc=0, scale=1, size=5)
print(arr)
Parameter Meaning
loc Mean
scale Standard deviation
size Shape of output

2D Normal Distribution

arr = random.normal(100, 20, size=(3, 3))
print(arr)

📦 Random Shuffle

Shuffle array elements in place

arr = np.array([1,2,3,4,5])
random.shuffle(arr)
print(arr)

📦 Random Permutation (Creates Copy)

arr = np.array([1,2,3,4,5])
perm = random.permutation(arr)
print(perm)

🔁 Seeding — Same Random Output Every Time

random.seed(42)

print(random.randint(100))

Useful in machine learning experiments to ensure reproducibility.


🧠 Summary Table

Function Purpose
random.rand() Random float (0–1)
random.randint() Random integer
random.random() Random floats array
random.choice() Pick random element(s)
random.normal() Normal distribution
random.shuffle() Shuffle original array
random.permutation() Shuffled copy
random.seed() Fix random results

🎯 Practice Tasks

# 1. Create a 4x4 array of random integers between 1–100
# 2. Shuffle the array
# 3. Generate 10 random even numbers between 50–100
# 4. Create a normal distribution with mean=500, std=50, size=1000

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 *