NumPy Generator-based Random Number Generation Cheatsheet
For information on the previous np.random API and its use cases, please refer to the NumPy documentation on legacy random generation: NumPy Legacy Random Generation
This cheatsheet focuses on the modern Generator-based approach to random number generation in NumPy.
Importing NumPy
Code
import numpy as np
Creating a Generator
Code
# Create a Generator with the default BitGeneratorrng = np.random.default_rng()# Create a Generator with a specific seedrng_seeded = np.random.default_rng(seed=42)
Basic Random Number Generation
Uniform Distribution (0 to 1)
Code
# Single random floatprint(rng.random())# Array of random floatsprint(rng.random(5))
# Single random integer from 0 to 10 (inclusive)print(rng.integers(11))# Array of random integers from 1 to 100 (inclusive)print(rng.integers(1, 101, size=5))
9
[11 69 90 28 33]
Normal (Gaussian) Distribution
Code
# Single value from standard normal distributionprint(rng.standard_normal())# Array from normal distribution with mean=0, std=1print(rng.normal(loc=0, scale=1, size=5))
# Random choice from an arrayarr = np.array([1, 2, 3, 4, 5])print(rng.choice(arr))# Random sample without replacementprint(rng.choice(arr, size=3, replace=False))
2
[3 5 2]
Shuffling
Code
arr = np.arange(10)rng.shuffle(arr)print(arr)
[1 4 9 7 0 6 8 3 5 2]
Other Distributions
Generators provide methods for many other distributions:
# Save statestate = rng.bit_generator.state# Generate some numbersprint("Original:", rng.random(3))# Restore state and regeneraterng.bit_generator.state = stateprint("Restored:", rng.random(3))
Use default_rng() to create a Generator unless you have specific requirements for a different Bit Generator.
Set a seed for reproducibility in scientific computations and testing.
Use the spawn() method to create independent generators for parallel processing.
When performance is critical, consider using the out parameter to fill existing arrays.
For very long periods or when security is important, consider using the PCG64DXSM Bit Generator.
Remember, Generators provide a more robust, flexible, and future-proof approach to random number generation in NumPy. They offer better statistical properties and are designed to work well in both single-threaded and multi-threaded environments.