NumPy Random Functions
In data science, simulations, gaming, and machine learning, random numbers play a crucial role — from
generating test data to splitting datasets and creating randomness in models. NumPy makes it super
easy to work with random numbers using its powerful random module. Whether you need a simple random
float, a shuffled array, or numbers following a specific distribution, NumPy provides a wide range of
functions to get the job done efficiently and reliably. Let’s explore some of the most useful NumPy
Random Functions you’ll use often.
1. rand( ) – Generate Random Float Numbers
What It Does :
The rand( ) function in NumPy is used to generate random float numbers between 0 and 1. The numbers are evenly distributed over this
range (i.e., uniform distribution).
It’s part of the numpy.random module.
Syntax :
numpy.random.rand(d0, d1, ..., dn)
- d0, d1, ..., dn are the dimensions of the array you want to create.
- If no argument is given, it returns a single float between 0 and 1.
Examples :
Generate a single random float :
import numpy as np
print(np.random.rand( ))
# Output: 0.7380231598689891 (random number)
Generate a 1D array of 5 random floats :
import numpy as np
print(np.random.rand(5))
# Output: [0.73802316 0.12345678 0.98765432 0.45678901 0.23456789]
Generate a 2D array (3 rows × 2 columns) :
import numpy as np
print(np.random.rand(3, 2))
# Output:
[[0.95645632 0.7948405 ]
[0.27238074 0.27654215]
[0.7343314 0.63809965]]
Key Points :
- Always generates numbers between 0 and 1 (excluding 1)
- Float values only
2. randint( ) – Generate Random Integers
What It Does :
randint( ) is used to generate random integers between a specified low (inclusive) and high (exclusive) range. You can also
specify how many numbers you want and in what shape (1D, 2D, etc.).
Syntax :
numpy.random.randint(low, high=None, size=None, dtype=int)
- low : Start of the interval (inclusive)
- high : End of the interval (exclusive). If not given, range is [0, low)
- size : Number or shape of output array
- dtype : The desired data type (default is int)
Examples :
Generate a single integer between 1 and 10 :
import numpy as np
print(np.random.randint(1, 10))
# Output: 7 (random)
Generate a 1D array of 5 random integers between 1 and 100 :
import numpy as np
print(np.random.randint(1, 100, size=5))
# Output: [12 45 78 34 23]
Generate a 2D array (3 rows × 4 columns) of random integers between 1 and 50 :
import numpy as np
print(np.random.randint(1, 50, size=(3, 4)))
# Output:
[[12 25 37 48]
[ 5 8 19 32]
[22 33 44 11]]
Use Cases :
- Simulations: Generate random samples for testing algorithms.
- Data Augmentation: Create synthetic data for training machine learning models.
- Games: Randomly place objects or generate levels.
- Statistical Sampling: Draw random samples from a population.
Key Points :
- Always returns integers
- Range is inclusive of low, but exclusive of high
- Works with multi-dimensional shapes
- Can be seeded using np.random.seed( ) for reproducibility
3. randn( ) – Generate Random Numbers from Standard Normal Distribution
What It Does :
randn( ) is used to generate random float numbers from the standard normal distribution, also known as a Gaussian distribution, where:
- Mean (μ) = 0
- Standard Deviation (σ) = 1
These numbers can be positive or negative and follow the familiar bell curve.
Syntax :
numpy.random.randn(d0, d1, ..., dn)
- d0, d1, ..., dn – Dimensions of the returned array
Examples :
Generate a single random number (standard normal distribution) :
import numpy as np
print(np.random.randn())
# Output: 0.123456789 (random)
Generate a 1D array of 5 random numbers :
import numpy as np
print(np.random.randn(5))
# Output: [ 0.73802316 -0.12345678 1.98765432 0.45678901 -0.23456789]
Generate a 2D array (3 rows × 4 columns) of random numbers :
import numpy as np
print(np.random.randn(3, 4))
# Output:
[[ 0.95645632 -0.7948405 1.27238074 0.27654215]
[ 0.7343314 -0.63809965 0.12345678 -1.98765432]
[-0.45678901 0.23456789 -0.12345678 1.98765432]]
Use Cases :
- Machine Learning: Initialize weights in neural networks.
- Statistical Analysis: Generate samples for hypothesis testing.
- Simulations: Model real-world phenomena that follow a normal distribution.
Key Points :
- Returns float numbers
- Numbers can be positive or negative
- Useful for statistical modeling and simulations
- Can be seeded for reproducibility
4. random( ) – Generate Random Floats Between 0 and 1
What It Does :
random( ) generates random float numbers from a uniform distribution between 0.0 (inclusive) and 1.0 (exclusive).
It’s useful when you want evenly distributed random numbers in that range.
Syntax :
numpy.random.random(size=None)
- size – The shape of the array to generate. If None, returns a single float.
Examples :
Generate a single random float :
import numpy as np
print(np.random.random())
# Output: 0.123456789 (random)
5. choice( ) – Randomly Select Elements from a Sequence
What It Does :
numpy.random.choice( ) allows you to randomly pick one or more elements from a given list, array, or range.
You can use it with or without replacement, and it's very useful for sampling, simulations, or generating random data.
Syntax :
numpy.random.choice(a, size=None, replace=True, p=None)
Parameters :
| Parameter |
Description |
a |
1D array-like or int. The source to choose from. |
size |
Number of items to pick (single int or tuple for multi-dim array). |
replace |
True (default): Same item can be chosen more than once.
False: No repeated selections.
|
p |
A list of probabilities associated with each entry in a. Must sum to 1.
|
Examples :
Pick one random item from a list :
import numpy as np
print(np.random.choice([10, 20, 30, 40]))
# Output: 30 (randomly selected)
Pick 3 random items with replacement :
np.random.choice([1, 2, 3, 4, 5], size=3)
# Output: [2, 4, 2]
Pick 3 random items without replacement :
np.random.choice([1, 2, 3, 4, 5], size=3, replace=False)
# Output: [1, 5, 3]
Pick items using custom probabilities :
np.random.choice([0, 1], size=10, p=[0.8, 0.2])
# Output: [0, 0, 1, 0, 0, 0, 0, 1, 0, 0]
Use Cases :
- Random sampling without modifying original data
- Simulating random events in games
- Creating random datasets for testing algorithms
6. shuffle( ) – Shuffle Elements Randomly
What It Does :
numpy.random.shuffle( ) randomly changes the order of elements in a NumPy array in-place, meaning it directly modifies the original array instead of returning a new one.
Syntax :
numpy.random.shuffle(arr)
- arr: The array you want to shuffle. Must be one-dimensional or the first axis of a multi-dimensional array is shuffled.
Examples :
Shuffle a 1D array :
import numpy as np
arr = np.array([10, 20, 30, 40, 50])
np.random.shuffle(arr)
print(arr)
# Output: [30 10 50 20 40] (Random result)
Shuffle along the first axis of a 2D array :
arr2d = np.array([[1, 2], [3, 4], [5, 6]])
np.random.shuffle(arr2d)
print(arr2d)
# Output: Rows will be shuffled randomly
# [[5 6]
# [1 2]
# [3 4]]
🔒 Note :
- shuffle( ) does not return anything; it modifies the original array.
- Only the first axis (rows) is shuffled in multi-dimensional arrays – not the inner elements.
Use Cases :
- Random sampling without modifying original data
- Simulating random events in games
- Creating random datasets for testing algorithms
7. seed( ) – Set Randomness for Reproducibility
What It Does :
numpy.random.seed( ) is used to set the seed value for NumPy's random number generator.
This ensures that the random numbers you generate are reproducible — meaning you’ll get the same random results every time you run the code.
Syntax :
numpy.random.seed(seed_value)
- seed_value: An integer. Use the same seed to get the same results.
Examples :
import numpy as np
np.random.seed(42)
print(np.random.randint(1, 100, 5))
# Output: [52 93 15 72 61] (same output every time)
np.random.seed(42)
print(np.random.randint(1, 100, 5))
# Output: [52 93 15 72 61] (same again!)
Why Use seed( )?
- Ensures consistent random output during debugging or teaching.
- Reproducibility in experiments and machine learning training.
- Good practice in writing test cases with controlled random behavior.
🔒 Important Notes :
- seed( ) controls only NumPy's random functions (not Python’s random module).
- Setting the same seed multiple times resets the random generator to the same state.