We use np.random.default_rng() to create a modern random number generator. It helps us get random numbers in a simple and reliable way.
np.random.default_rng() modern approach in NumPy
rng = np.random.default_rng(seed=None)seed is optional. If you give a number, you get the same random numbers every time.
This method is recommended over older np.random functions for better randomness and features.
import numpy as np rng = np.random.default_rng() print(rng.integers(1, 10))
rng = np.random.default_rng(seed=42) print(rng.random())
rng = np.random.default_rng() sample = rng.choice([10, 20, 30, 40], size=2, replace=False) print(sample)
This program shows how to create a modern random number generator with a seed. It generates random integers, random floats, and shuffles a list.
import numpy as np # Create a random number generator with a fixed seed rng = np.random.default_rng(seed=123) # Generate 5 random integers between 0 and 99 random_integers = rng.integers(0, 100, size=5) # Generate 3 random floats between 0 and 1 random_floats = rng.random(3) # Randomly shuffle a list data = [1, 2, 3, 4, 5] rng.shuffle(data) print("Random integers:", random_integers) print("Random floats:", random_floats) print("Shuffled list:", data)
Using a seed makes your random results repeatable, which is useful for debugging.
The default_rng() method is faster and more flexible than older random functions.
Always use default_rng() for new projects instead of np.random.seed() or np.random.rand().
np.random.default_rng() creates a modern random number generator.
It supports many random operations like integers, floats, shuffling, and sampling.
Using a seed gives you the same random numbers every time you run the code.