NumPy – Understanding random.Generator.random() method (5 examples)

Updated: February 28, 2024 By: Guest Contributor Post a comment

Introduction

NumPy is an essential library in the Python data science stack, providing support for large, multi-dimensional arrays and matrices, along with a collection of mathematical functions to operate on these arrays. One of the interesting submodules it includes is numpy.random, which contains functions for generating random numbers. In this tutorial, we will specifically focus on the random.Generator.random() method, diving into its use through five comprehensive examples.

Syntax & Parameters

The random.Generator.random() method is part of NumPy’s new random number generator system, introduced in version 1.17. This system provides several advantages over the older numpy.random functions, including improved statistical properties, more features, and better performance. The method generates random numbers in a half-open interval [0.0, 1.0), meaning it includes 0.0 but excludes 1.0.

Syntax:

# Create a random generator first
rng = np.random.default_rng()

# Then
rng.random(size=None, dtype=np.float64, out=None)

Where:

  • size: Optional. The shape of the output array. It can be an integer or a tuple of integers. If not provided, a single float is returned.
  • dtype: Optional. The desired data-type for the output. Default is np.float64. Other options include np.float32, etc.
  • out: Optional. An alternative output array in which to place the result. This must have a shape that the inputs broadcast to.

Now, let’s dive into the examples. Each example will gradually increase in complexity, showcasing different aspects and applications of random.Generator.random().

Example 1: Basic Random Numbers

import numpy as np

# Create a generator
generator = np.random.default_rng()

# Generate a single random number
single_random_number = generator.random()
print(f'Single random number: {single_random_number}')

# Generate an array of 5 random numbers
random_numbers_array = generator.random(5)
print(f'Array of 5 random numbers: {random_numbers_array}')

Output (vary due to the randomness):

Single random number: 0.4863495393659324
Array of 5 random numbers: [0.85578134 0.72474327 0.17802284 0.09173301 0.73784029]

This example demonstrates how to generate a single random number and an array of random numbers. Note the use of default_rng(), which creates an instance of the generator.

Example 2: Setting the Shape of the Random Array

import numpy as np

# Create a generator
generator = np.random.default_rng()

# Generate a 2x3 array of random numbers
random_2x3 = generator.random((2, 3))
print(f'2x3 array of random numbers:\n{random_2x3}')

Output (it will change each time you re-run your code):

2x3 array of random numbers:
[[0.02671052 0.42950942 0.9637756 ]
 [0.98498732 0.5616961  0.0231519 ]]

Here, we specify the shape of the array (2×3) directly in the random() method by passing a tuple. This functionality is useful for creating multi-dimensional random arrays for simulations or data analysis.

Example 3: Generating Numbers with Specific Distribution

The random.Generator supports various distributions such as normal, exponential, and binomial. Though random() generates numbers uniformly, we can use it in combination with other functions to simulate different distributions.

import numpy as np

# Create a generator
generator = np.random.default_rng()

# Simulate numbers from a normal distribution
mean = 0
std_dev = 1
# Corrected the typo from 'meannprint' to 'mean' and separated the print statement
normal_numbers = std_dev * generator.standard_normal(5) + mean
print(f'Normal distributed numbers: {normal_numbers}')

Output (random):

Normal distributed numbers: [ 1.02885687  1.64192004  1.14671953 -0.97317952 -1.3928001 ]

In this example, though we aren’t using random() directly, the generator.standard_normal() method demonstrates another way to generate random numbers, this time from a normal distribution.

Example 4: Random Sampling with Replacement

Sometimes, you may want to perform random sampling from an array, possibly with replacement. The random.Generator provides a straightforward method to achieve this.

import numpy as np

# Create a generator
generator = np.random.default_rng()

# Generate a sample array
sample_array = np.array(['apple', 'banana', 'cherry', 'date', 'elderberry'])

# Random sampling with replacement
sampled = generator.choice(sample_array, size=5, replace=True)
print(f'Sampled with replacement: {sampled}')

Output (random):

Sampled with replacement: ['banana' 'date' 'apple' 'banana' 'banana']

This example uses the choice() method to perform sampling with replacement. It’s a powerful tool for simulations where you need to simulate the outcome of experiments multiple times.

Example 5: Seed for Reproducibility

Ensuring reproducibility is an important aspect of scientific computation. The random.Generator.random() method allows for setting a seed, ensuring that the sequence of random numbers can be reproduced.

import numpy as np

# Create a generator with a seed
generator = np.random.default_rng(seed=42)

# Generate a random number
random_number = generator.random()
print(f'Reproducible random number: {random_number}')

Output:

Reproducible random number: 0.7739560485559633

In this example, we initialize the generator with a specific seed. Any subsequent calls to the generator will produce the same sequence of numbers, provided the seed and the sequence of commands remain unchanged.

Conclusion

The random.Generator.random() method from NumPy offers a flexible and powerful way to generate random numbers for a wide range of applications, from the most basic simulations to complex, high-dimensional data analysis. Understanding how to harness this functionality is an invaluable skill in the arsenal of any data scientist or engineer.