NumPy Random Module – 6 Ways to Generate Random Numbers

NumPy provides a random module that allows users to create random integers, floats, and arrays for various applications, such as simulations, machine learning, and statistical analysis.

The numpy.random module implements pseudo-random number generators (PRNGs for short) with the ability to draw samples from a variety of probability distributions.

The random module includes functions to create random integers, floats, and samples from various probability distributions, making it efficient for handling large datasets.

Applications

Random numbers help in creating random datasets, performing random sampling, and simulating random processes. The list below shows a few applications where random numbers ar useful.

ApplicationUsed For
Data ScienceRandom Sanpling
Game DevelopmentFor generating random positions of objects
Statistical SimulationsSimulating random processes
Machine Learning
Applications of Random Numbers

What are Pseudo-random numbers

Random numbers are values generated in a way that cannot be predicted logically. These are often referred to as pseudo-random numbers because they are generated by algorithms that can produce sequences of numbers that appear random but are actually determined by an initial value known as a seed.

What are Seeds in Random Number Generation

Seeds are numbers used to initialize a pseudo-random number generator (PRNG). They serve as the starting point for generating a sequence of numbers that appear random.

  • Seed completely determines the number generated by pseudo-random generator.
  • If the same seed is used to generate random number again, the result will be same random number

NumPy Random Module methods

numpy.random module has several methods. Here are a few NumPy’s random module’s methods:

MethodDescriptionExample Code
random.randint(low, high)
Generates a random integer between low (inclusive) and high (exclusive). x = random.randint(0, 100)
Generates a random nimber between 0 and 100
random.rand()Generates a random float between 0 and 1x = random.rand() Generates a floating-point number between 0 and 1.
random.rand(size)Generates an array of random floats of specified sizex = random.rand(3, 5)
Generates an 3X5 array.
random.choice(array)Returns a random value from an arrayx = random.choice([1, 2, 3, 4], size = (n1, n2))

The following programs show how to generate random numbers and random arrays using the above methods.

random.randint(low, high) Method

Syntax: random.randint(lowhigh=Nonesize=Nonedtype=int)

ParameterDescription
lowint or array of ints
highint or array of ints, (optional). If high is None (the default), then results are from [0, low).
sizeint or tuple of ints (optional).
dtypeDesired dtype of the result (optional)

Returns: The function returns and int or ndarray of ints. Returns size-shaped array of random integers or a single such random int if size is not provided.

Program Example: random.randint() Function to Generate a Random Integer

The program below generates a random integer between 0 and 50.

# Random INTEGER creation
print("PROGRAM NAME: random_int.py")
from numpy import random
# Generate an integer between 0 and 50
randomInteger = random.randint(50)
print("A random number between 0 and 50 is: \n", randomInteger)

The following is the program’s output:

PROGRAM NAME: random_int.py
A random number between 0 and 50 is:
41

If you run this program again, you will get a different random number.

random.rand() Method

This function generates random numbers from a uniform distribution over the interval [0, 1). If size is specified, it create an array of the given shape and populate it with random samples from a uniform distribution over [0, 1).

Applications:

By utilizing numpy.random.rand, you can incorporate randomness into your data analysis and computational tasks for initializing random matrices in machine learning models

The program below generates a random floating-point number between 0 and 1.

Program Example: nmpy.random.rand() Function to Generate a Random Floating-point Number

# Random FLOATING POINT NUMBER CREATION
print("PROGRAM NAME : random_fp.py \n")
from numpy import random
# Generate a floating point number between 0 and 1
randomFP = random.rand()
print("A random floating point number between 0 and 1 is: \n", randomFP)
print()

The following is the program’s output. If you run this program again, you will get a different random floating-point number.

PROGRAM NAME : random_fp.py

A random floating-point number between 0 and 1 is :  0.16129247678968606

Program Example: numpy.random.rand(size) Function to Generate a 2-D Array

The program below uses Random module’s rand() method to generate an array of a specified shape.  The size parameter is used to specify the shape of the array (the dimensions for the rows and columns).

# Random FLOATING POINT NUMBER  ARRAY CREATION
print("PROGRAM NAME : random_array.py \n")
from numpy import random
# Generate a floating point random array of size 2x4.
randomFPArray = random.rand(2, 4)
print("A random  floating point 2X4 array between 0 and 1 is: \n", randomFPArray)

The following is the program’s output:

PROGRAM NAME : random_array.py

A random floating point 2X4 array between 0 and 1 is:
[[0.95716797 0.69381207 0.97400157 0.89539055]
[0.70024386 0.18370245 0.62393143 0.15132604]]

random.choice() method

The numpy.random.choice function is used to randomly select elements from an array or a list. You can select size of the output and the dimension of the output.

Random.choice method allows you to select:

  • The number of items to select
  • Allow multiple selection: Whether the same item can be selected multiple items
  • Probability of selection: You can assign the probability of selection of each item.

Applications:

random.choice() function is used in data science, machine learning, and statistical analysis for random sampling and simulations.

Syntax: numpy.random.choice(array, size=None, replace=True, p=None)

PARAMETERDESCRIPTIONNOTES
arrayarray from which elements are selected
SizeSpecify the Size of the output (dimension). It determines the output shape. 
replacereplace = True specifies that a selected element can be selected again.  replace=False specifies that an element once selected cannot be selected again.Optional.
Default = True
pParameter p specifies the probability associated with the selection of an element in the list. Sum of all probabilities must equal 1.Optional.
If p is not specified, selection for elements has equal probabilities.

The program #1 below uses the choice() method to generate a random value from an array of values.

In the Program #2 below the choice() method takes an array “array1d” as a parameter and randomly returns one of the values.

Generate a random 1-D array selecting elements from a list.

# Random CHOICE 1D
print("PROGRAM NAME: numpy_random_choce_1d \n")
import numpy as np
from numpy import random
# PROGRAM 1: choice() method to generate a random value from list [2, 7, 8, 5, 8].
a = random.choice([2, 7, 8, 5, 9])
print("Number randomly selected by random.choice method from the list is: \n", a)
print()
#PROGRAM 2: array1d is taken as a parameter by choice() method 
# and randomly returns one of the values from array 'array1d'.
array1d = np.arange(0, 15, 3)
# First print array1d
print("1-D array of 5 elements between 0 and 15 spaced by 3 is: \n" , array1d)
print()
# Use random.choice to randomly generate a number from array1d.
b = random.choice(array1d)
print("Number randomly selected by random.choice method from aeeay1d is: \n", b)
print()
# Use random.choice to randomly generate an array from array1d.
c = random.choice(array1d, size = 4)
print("1-D array of size 4 randomly selected from array1d is: \n", c)

The following is the program’s output:

PROGRAM NAME: numpy_random_choce_1d

Number randomly selected by random.choice method from the list is:
8

1-D array of 5 elements between 0 and 15 spaced by 3 is:
[ 0 3 6 9 12]

Number randomly selected by random.choice method from aeeay1d is:
0

1-D array of size 4 randomly selected from array1d is:
[ 0 12 9 12]

The program below generates 2-D array by randomly selecting elements from a list of numbers.

random.choice Method to Generate a Random 2D array from a List

# Random CHOICE 2D
print("PROGRAM NAME: numpy_random_choice_2d \n")
import numpy as np
from numpy import random
####
list = ([2, 5, 9, 6, 1])
print("list is: \n", list)
print()
# Create a 2D array of sze 2x4 from a list of numbers [2, 5, 9, 6, 1]
array2d = random.choice([2, 5, 9, 6, 1], size = (2, 4))
print("A 2x4 array generated by random.choice method from list is: \n", array2d)
print("----- End of random.choice 2x4 array ------\n")
##
print("Generate 2-D 2x2 array from the list allowing multiple selection. \n")
arr_multiple = np.random.choice(list, size = (2, 2), replace = False)
print("A 2-D 3x2 array from list allowing multiple selection is: \n", arr_multiple)
print(" ----- End of random.choice multiple selection -----")
print()
print("Generate a 2-D 4x2 array using random.choice function")
print("specifying probabilitoes of selection. \n")
arr_prob = np.random.choice(list, size = (4, 2), p =[0.1, 0.3, 0.2, 0.3, 0.1])
print("2-D 4x2 array from list using random.choice with probabilitie is:" , arr_prob)

The following is the random.choice() program’s output:

PROGRAM NAME: numpy_random_choice_2d

list is:
[2, 5, 9, 6, 1]

A 2×4 array generated by random.choice method from list is:
[[1 5 9 2]
[5 5 2 2]]
—– End of random.choice 2×4 array ——

Generate 2-D 2×2 array from the list allowing multiple selection.

A 2-D 3×2 array from list allowing multiple selection is:
[[6 1]
[9 5]]
—– End of random.choice multiple selection —–

Generate a 2-D 4×2 array using random.choice function
specifying probabilitoes of selection.

2-D 4×2 array from list using random.choice with probabilitie is: [[6 2]
[2 9]
[2 9]
[6 6]]

Verified by MonsterInsights