NumPy Random Functions Explained (rand, randn, ranf, randint)
Random numbers are widely used in real-world applications like simulations, testing, AI models, and games.
🔹 Step 1: Import Libraries
import numpy as np import random
Note: Most work here is done using np.random
🔹 1. rand() → Uniform Random Values
ar = np.random.rand(2,2) print(ar)
✅ Explanation:
- Generates numbers between 0.0 to 1.0
- Values are uniformly distributed
(2,2)→ 2 rows, 2 columns
💡 Real Scenario:
Generating random probabilities → e.g., simulate user click chance in a system
⚠️ Important Points:
rand(2)→ 1D arrayrand(1,2)→ 2D array- More values = higher dimensions
🔹 2. randn() → Normal Distribution (Gaussian)
ar = np.random.randn(2,3) print(ar)
✅ Explanation:
- Values are centered around 0
- Can be positive or negative
- Follows normal distribution (bell curve)
💡 Real Scenario:
Used in Machine Learning → weight initialization in neural networks
⚠️ Important:
- Most values are close to 0
- Few extreme values (like -2, +2)
🔹 3. ranf() → Random Float Sampling
ar = np.random.ranf(2) print(ar)
✅ Explanation:
- Generates values between 0.0 to 1.0
- Very similar to
rand()
💡 Real Scenario:
Used in simulations → random sampling of probabilities
⚠️ Important:
- Returns 1D array if single value passed
- Difference from rand() is minimal for beginners
🔹 4. randint() → Random Integers
ar = np.random.randint(2,10,3) print(ar)
✅ Explanation:
- Generates integers from 2 to 9 (10 excluded)
3→ total numbers
💡 Real Scenario:
Generating OTPs, random IDs, dice rolls, game scores
⚠️ Important Points:
- Upper bound is always excluded
- Works only with integers
🔥 Key Differences (Quick View)
- rand() → uniform (0 to 1)
- randn() → normal distribution (around 0)
- ranf() → random floats (0 to 1)
- randint() → random integers
🚀 Pro Tips
- Use rand() for probability simulations
- Use randn() for ML models
- Use randint() for discrete values
- Set seed for same output every time:
np.random.seed(42)
👉 Useful for debugging & reproducibility
❌ Common Mistakes
- Confusing rand() and randn()
- Forgetting upper limit is excluded in randint()
- Assuming ranf() is very different from rand()
🔚 Conclusion
Random functions are essential when working with simulations, testing, and AI systems.
Mastering them helps you build real-world applications faster ⚡