π Introduction
Random numbers are widely used in:
- Machine Learning
- Simulations
- Data sampling
With NumPy, generating random data is fast and simple.
π Why Use NumPy Random Module?
It helps you:
- Generate random datasets
- Perform simulations
- Test algorithms
π§ͺ Import Random Module
import numpy as np
π² 1. Generate Random Integers (randint())
print(np.random.randint(1, 10, size=5))
π Output (example):
[3 7 1 9 5]
β Generates random integers
π 2. Random Float Numbers (rand())
print(np.random.rand(3))
π Output:
[0.23 0.67 0.45]
β Values between 0 and 1
π’ 3. Random Choice (choice())
arr = [10, 20, 30, 40]print(np.random.choice(arr))
β Picks random value from array
π 4. Shuffle Data (shuffle())
arr = np.array([1, 2, 3, 4])np.random.shuffle(arr)
print(arr)
β Shuffles array in-place
π 5. Generate Random Samples (normal())
print(np.random.normal(loc=0, scale=1, size=5))
β Generates normally distributed data
π― 6. Set Random Seed (Important)
np.random.seed(42)
print(np.random.randint(1, 10, 3))
β Ensures same output every time
β‘ Why Use NumPy?
Using NumPy:
- Fast random generation
- Supports large datasets
- Multiple distributions available
π¦ Real-World Use Case
# Simulate dice roll
dice = np.random.randint(1, 7, size=10)
print(dice)
β Used in:
- Game development
- Simulations
- AI models
π Works with Other Libraries
Random data is used in:
- Scikit-learn
- TensorFlow
- Pandas
π Summary Table
| Function | Description |
|---|---|
| randint() | Random integers |
| rand() | Random floats |
| choice() | Random selection |
| shuffle() | Shuffle array |
| normal() | Normal distribution |
π§ Pro Tips
- Use
seed()for reproducibility - Choose distribution based on use case
- Combine with NumPy arrays for simulations
π Conclusion
The random module in NumPy is essential for simulations, testing, and machine learning.