NumPy - Random Generator



NumPy Random Generator

The random generator in NumPy is used to generate random numbers and perform random sampling.

The random module in NumPy offers a wide range of random number generation functions, from generating random integers and floating-point numbers to more complex distributions like normal, uniform, and binomial distributions.

In this tutorial, we will explore how to use the NumPy Random Generator to generate random data and discuss the important functions available in this module.

The NumPy Random Module?

The NumPy random module is a submodule within the NumPy library that contains functions for generating random numbers, performing random sampling, and generating random distributions. It provides the numpy.random package, which supports the creation of random numbers from various probability distributions like uniform, normal, and binomial.

By using NumPy's random generator, we can generate random values that can be used for simulations, randomized testing, or even cryptographic operations. The random numbers generated are pseudo-random, meaning they are generated using a deterministic process but appear random.

The sequence of random numbers can be controlled using a random seed, which ensures reproducibility in simulations and experiments.

How Does NumPy's Random Generator Work?

The NumPy random number generator is built on top of a pseudorandom number generator (PRNG) algorithm called the Mersenne Twister. The key feature of a PRNG is that it generates a sequence of numbers that approximates true randomness, but it is determined by an initial value, called a seed.

By setting the same seed, you can ensure that the sequence of random numbers is the same every time you run your code, which is important for reproducibility in scientific experiments.

Seeding the Random Generator

To control the random number generation process, NumPy provides the numpy.random.seed() function, which sets the seed for the random number generator. This allows you to generate the same random numbers every time you run your program.

Example

In the example below, by setting the same seed value (42 in this case), we get the same sequence of random numbers every time we run the code. This helps in ensuring consistency during experiments and debugging −

import numpy as np

# Set the seed for reproducibility
np.random.seed(42)

# Generate random numbers
random_numbers_1 = np.random.random(5)

# Generate the same random numbers with the same seed
np.random.seed(42)
random_numbers_2 = np.random.random(5)

# Display the results
print("First random numbers:", random_numbers_1)
print("Second random numbers:", random_numbers_2)

Following is the output obtained −

First random numbers: [0.37454012 0.95071431 0.73199394 0.59865848 0.15601864]
Second random numbers: [0.37454012 0.95071431 0.73199394 0.59865848 0.15601864]

Generating Random Numbers

NumPy offers various functions for generating random numbers. Here, we will explore some of the most commonly used functions −

Random Float Numbers

The numpy.random.random() function generates random floating-point numbers between 0 and 1. You can specify the shape of the output array by passing the desired dimensions as an argument. For example −

import numpy as np

# Generate 5 random float numbers between 0 and 1
random_floats = np.random.random(5)
print("Random float numbers:", random_floats)

The result produced is as follows −

Random float numbers: [0.96177309 0.75071326 0.44828032 0.53441928 0.56717514]

Random Integers

The numpy.random.randint() function generates random integers within a specified range. You can specify the low and high values, and it will return integers between the low (inclusive) and high (exclusive) values. Here is an example −

import numpy as np

# Generate 5 random integers between 10 (inclusive) and 100 (exclusive)
random_integers = np.random.randint(10, 100, size=5)
print("Random integers:", random_integers)

After executing the above code, we get the following output −

Random integers: [13 38 56 94 78]

Random Numbers from Normal Distribution

The numpy.random.normal() function generates random numbers from a normal (Gaussian) distribution with a specified mean and standard deviation. You can also specify the size of the output array. Here's how it works −

import numpy as np

# Generate 5 random numbers from a normal distribution with mean=0 and std=1
random_normal = np.random.normal(0, 1, 5)
print("Random numbers from normal distribution:", random_normal)

The output obtained is as shown below −

Random numbers from normal distribution: [ 0.52379705  0.3169246   0.76473415 -0.73006407 -0.50259886]

Random Numbers from Uniform Distribution

The numpy.random.uniform() function generates random numbers from a uniform distribution within a given range. Here's an example of generating 5 random numbers between 1.0 and 10.0

import numpy as np

# Generate 5 random numbers between 1.0 and 10.0
random_uniform = np.random.uniform(1.0, 10.0, 5)
print("Random numbers from uniform distribution:", random_uniform)

The result produced is as follows −

Random numbers from uniform distribution: [4.92412702 2.57524084 1.71870242 3.71017627 6.19920522]

Random Sampling with Replacement

Sometimes, we need to randomly select elements from an array. NumPy provides the numpy.random.choice() function, which allows you to perform random sampling with or without replacement.

Example

In the example below, the function selects 3 random elements from the array with replacement, meaning elements can be selected multiple times −

import numpy as np

# Define an array of elements
array = np.array([1, 2, 3, 4, 5])

# Randomly select 3 elements from the array with replacement
sample_with_replacement = np.random.choice(array, 3, replace=True)
print("Random sample with replacement:", sample_with_replacement)

The result produced is as follows −

Random sample with replacement: [5 3 5]

Shuffling an Array

Another useful operation is shuffling the elements of an array randomly. NumPy provides the numpy.random.shuffle() function for this purpose. It randomly permutes the elements of an array in-place.

Example

In the following example, we are shuffling an array in NumPy using the numpy.random.shuffle() function −

import numpy as np

# Define an array
array = np.array([1, 2, 3, 4, 5])

# Shuffle the array in place
np.random.shuffle(array)
print("Shuffled array:", array)

The output obtained is as shown below −

Shuffled array: [4 2 3 5 1]
Advertisements