NumPy – Random Generator
Random numbers are widely used in programming and data science for:
- Simulations
- Machine learning
- Data sampling
- Gaming
- Testing algorithms
In NumPy, randomness is handled using the np.random module.
Modern NumPy recommends using np.random.default_rng() for better randomness control.
What is a Random Generator?
A random generator produces numbers that appear unpredictable.
In simple terms: It creates random values for simulations and testing.
Import NumPy
import numpy as np
1. Generate Random Integers
import numpy as np
rng = np.random.default_rng()
random_numbers = rng.integers(1, 10, size=5)
print(random_numbers)
Output (example):
[3 7 1 9 5]
2. Generate Random Floats
import numpy as np
rng = np.random.default_rng()
random_floats = rng.random(5)
print(random_floats)
Output (example):
[0.23 0.89 0.12 0.67 0.45]
3. Generate Random 2D Array
import numpy as np
rng = np.random.default_rng()
A = rng.random((3, 3))
print(A)
4. Random Choice from Array
import numpy as np
rng = np.random.default_rng()
data = np.array([10, 20, 30, 40, 50])
sample = rng.choice(data, size=3)
print(sample)
5. Shuffle Array Elements
import numpy as np
rng = np.random.default_rng()
A = np.array([1, 2, 3, 4, 5])
rng.shuffle(A)
print(A)
6. Random Normal Distribution
import numpy as np
rng = np.random.default_rng()
data = rng.normal(loc=0, scale=1, size=5)
print(data)
Meaning:
- loc = mean
- scale = standard deviation
7. Random Seed (Reproducibility)
import numpy as np
rng = np.random.default_rng(42)
print(rng.random(3))
Why seed is important?
It ensures the same random results every time.
Real-World Applications
1. Machine Learning
- Train/test data split
- Weight initialization
2. Data Science
- Sampling datasets
- Simulations
3. Gaming
- Random events
- Procedural generation
4. AI Research
- Stochastic models
- Monte Carlo simulations
Why Use NumPy Random Generator?
Using NumPy provides:
- Fast random number generation
- Multiple distributions
- Reproducible results with seeds
- Efficient large-scale array support
Combined with Python, it becomes essential for AI, ML, and data science.
Old vs New Random System
| Method | Status |
|---|---|
| np.random.* | Legacy |
| default_rng() | Recommended |
Summary
NumPy provides a powerful random generator using:
rng = np.random.default_rng()
It supports integers, floats, distributions, and sampling.
Conclusion
The NumPy random generator is a core tool for simulations, machine learning, and statistical modeling. It makes generating random data fast, flexible, and reliable.


0 Comments