๐ 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.