The numpy.random module implements pseudo-random number generators (PRNGs) with the ability to draw samples from a variety of probability distributions.
Create a Generator instance with default_rng and call its methods:
import numpy as np# Create a generatorrng = np.random.default_rng()# Generate random floats in [0, 1)rng.random()# 0.06369197489564249# Generate array from standard normal distributionrng.standard_normal(10)# array([-0.31, -1.89, -0.36, ...])# Generate random integersrng.integers(low=0, high=10, size=5)# array([8, 7, 6, 2, 0])
Container for BitGenerators that provides access to distributions.Parameters:
bit_generator : BitGenerator - Core RNG engine
Example:
import numpy as npfrom numpy.random import Generator, PCG64# Create with specific BitGeneratorrng = Generator(PCG64(seed=12345))# Use methodsprint(rng.normal(0, 1, size=5))print(rng.integers(0, 100, size=10))
Use default_rng() instead of constructing Generator directly unless you need a specific BitGenerator.
import numpy as np# Same seed = same sequencerng1 = np.random.default_rng(42)rng2 = np.random.default_rng(42)for i in range(5): print(f"{rng1.random():.6f} == {rng2.random():.6f}")
The pseudo-random number generators in this module are designed for statistical modeling and simulation, not security or cryptography. Use Python’s secrets module for security purposes.
# DON'T use for securityimport numpy as nprng = np.random.default_rng()insecure_token = rng.integers(0, 1000000) # ❌ Predictable# DO use secrets moduleimport secretssecure_token = secrets.randbelow(1000000) # ✓ Cryptographically secure