NumPy Random Generator (RNG)

NumPy's random generator API provides a powerful and flexible way to generate random numbers, samples, and sequences. The new Generator class (introduced in NumPy 1.17) replaces the legacy random functions with a modern, reproducible, and statistically robust approach.

Key Features of NumPy's Random Generator

  • Reproducibility: Easily create reproducible random sequences by setting seeds.
  • Wide variety of distributions: Generate random numbers from uniform, normal, binomial, Poisson, and many more distributions.
  • Performance: Efficient and well-optimized for scientific computing and simulations.
  • Flexible API: Use methods on the Generator instance for all random operations.

Understanding how to use NumPy's Generator will empower you to simulate data, initialize models, perform stochastic sampling, and experiment with randomness in your scientific and machine learning projects.


Creating a Random Generator Instance

The recommended way to create a random number generator in NumPy is to use the default_rng() function. This function returns an instance of the Generator class, which provides modern, flexible random number generation.

python
import numpy as np

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

# Generate a random float between 0 and 1
random_float = rng.random()

print(random_float)

How It Works:

  • np.random.default_rng() creates a new Generator instance using a high-quality default bit generator.
  • The Generator instance rng provides many methods for generating random numbers from different distributions.
  • rng.random() returns a random float in the half-open interval [0.0, 1.0).
  • You can create reproducible sequences by passing a seed to default_rng(), e.g., default_rng(42).

Output

0.3745401188473625

💡 Tip: Using default_rng() is preferred over the legacy np.random.seed() and global random functions for better statistical properties and clearer code.


Generating Random Floats with rng.random()

The random() method of the Generator instance generates random floats in the half-open interval [0.0, 1.0). You can generate a single float or an array of floats by specifying the size parameter.

python
import numpy as np

rng = np.random.default_rng()

# Generate a single random float
single_float = rng.random()

# Generate a 1D array of 5 random floats
array_floats = rng.random(size=5)

print("Single float:", single_float)
print("Array of floats:", array_floats)

How It Works:

  • rng.random() returns floats in the range [0.0, 1.0).
  • The size parameter controls the shape of the output. For example, size=5 returns an array of 5 floats.
  • If size is omitted, a single float is returned.

Output

Single float: 0.5488135039273248
Array of floats: [0.71518937 0.60276338 0.54488318 0.4236548  0.64589411]

💡 Tip: Use rng.random() when you need uniformly distributed floats for simulations, initializing weights, or any case requiring random numbers between 0 and 1.


Generating Random Integers with rng.integers()

The integers() method of the Generator instance generates random integers from a specified range. By default, the range is [low, high) (high is exclusive), but you can set endpoint=True to include the upper bound.

python
import numpy as np

rng = np.random.default_rng()

# Generate a single random integer from 0 to 10, excluding 10
single_int_exclusive = rng.integers(low=0, high=10)

# Generate a single random integer from 0 to 10, including 10
single_int_inclusive = rng.integers(low=0, high=10, endpoint=True)

# Generate a 1D array of 5 random integers between 10 and 20, including 20
array_ints = rng.integers(low=10, high=20, endpoint=True, size=5)

print("Single int (exclusive):", single_int_exclusive)
print("Single int (inclusive):", single_int_inclusive)
print("Array of ints (inclusive):", array_ints)

How It Works:

  • low specifies the inclusive lower bound.
  • high specifies the upper bound, exclusive by default.
  • Set endpoint=True to include high in the possible output values.
  • size controls the shape of the output; omit for a single integer.

Output (example)

Single int (exclusive): 3
Single int (inclusive): 10
Array of ints (inclusive): [12 17 10 20 14]

💡 Tip: The endpoint option is useful when you want an inclusive range, such as when generating random indices that include the last element.


Frequently Asked Questions

What is NumPy's random Generator?

NumPy's random Generator is a modern interface introduced in version 1.17 for generating random numbers. It is accessed via np.random.default_rng() and offers improved performance and reproducibility.


What is the difference between default_rng and np.random?

default_rng() returns a Generator instance with better statistical properties and no reliance on global state. In contrast, older functions like np.random.rand() share global state and can cause unexpected results in concurrent or large applications.


How do I generate random integers in NumPy?

Use rng.integers(low, high) to generate integers in a specified range. You can pass size for arrays and use endpoint=True to include the upper bound.


Can I reproduce results using default_rng?

Yes. Pass a fixed seed like default_rng(42) to ensure that you get the same sequence of random numbers each time you run your code.


Why should I use default_rng over np.random.seed?

default_rng avoids shared global state, provides better randomness, and is more modular. It's the preferred method since NumPy 1.17 and supports multiple independent generators.



What's Next?

Up next, we’ll explore Random Sampling in NumPy — a fundamental technique used to draw samples from arrays. You'll learn how to perform sampling with and without replacement, control probabilities.