Generating random numbers is essential in simulations, games, testing, and many data science applications. NumPy provides a powerful random
module with many functions for generating random numbers, arrays, and distributions.
import numpy as np
# You can use random functions with np.random
np.random.rand()
: Uniform distribution over [0, 1)np.random.randint(low, high)
: Random integer between low
(inclusive) and high
(exclusive)np.random.random()
: Another way to get float in [0, 1)# Random float between 0 and 1
print(np.random.rand()) # e.g., 0.374540
# Random integer between 10 and 20
print(np.random.randint(10, 20)) # e.g., 13
# Another random float [0,1)
print(np.random.random()) # e.g., 0.950714
You can generate arrays filled with random values:
# 1D array of 5 random floats [0,1)
arr1 = np.random.rand(5)
print(arr1)
# 2D array 3x4 with random floats
arr2 = np.random.rand(3, 4)
print(arr2)
# 1D array of 5 random integers between 0 and 10
arr3 = np.random.randint(0, 10, size=5)
print(arr3)
NumPy lets you sample from many common probability distributions:
np.random.normal(loc=0.0, scale=1.0, size=None)
: Normal (Gaussian) distribution with mean loc
and std deviation scale
.np.random.uniform(low=0.0, high=1.0, size=None)
: Uniform distribution over [low, high).np.random.choice(a, size=None, replace=True, p=None)
: Random sample from 1D array a
.# 5 samples from normal distribution (mean=0, std=1)
samples = np.random.normal(0, 1, 5)
print(samples)
# 5 samples from uniform distribution between 10 and 20
uniform_samples = np.random.uniform(10, 20, 5)
print(uniform_samples)
# Random choice from list ['a','b','c','d'], 4 picks, no replacement
choices = np.random.choice(['a', 'b', 'c', 'd'], 4, replace=False)
print(choices)
Random numbers are generated using a pseudo-random number generator. To get the same random numbers every run (helpful for debugging), you can set a seed:
np.random.seed(42) # Fix the seed number
print(np.random.rand(3)) # Will always generate same output on every run
Function | Description | Example |
---|---|---|
np.random.rand(d0, d1, ...) |
Random floats in [0,1) in given shape | np.random.rand(2,3) |
np.random.randint(low, high, size) |
Random integers in [low, high) | np.random.randint(5, 15, size=4) |
np.random.normal(loc, scale, size) |
Random floats from normal distribution | np.random.normal(0, 1, 5) |
np.random.uniform(low, high, size) |
Random floats from uniform distribution | np.random.uniform(0, 10, 5) |
np.random.choice(a, size, replace, p) |
Random samples from array a |
np.random.choice([1,2,3,4], 3, False) |
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!