0
0
NumPydata~5 mins

np.random.default_rng() modern approach in NumPy

Choose your learning style9 modes available
Introduction

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.

When you want to generate random numbers for simulations or games.
When you need random samples from data for testing or training models.
When you want to shuffle or mix data randomly.
When you want reproducible random results by setting a seed.
When you want to replace older random functions with a better method.
Syntax
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.

Examples
Create a random number generator and print a random integer from 1 to 9.
NumPy
import numpy as np
rng = np.random.default_rng()
print(rng.integers(1, 10))
Create a generator with a seed for reproducible random float between 0 and 1.
NumPy
rng = np.random.default_rng(seed=42)
print(rng.random())
Randomly pick 2 unique items from a list.
NumPy
rng = np.random.default_rng()
sample = rng.choice([10, 20, 30, 40], size=2, replace=False)
print(sample)
Sample Program

This program shows how to create a modern random number generator with a seed. It generates random integers, random floats, and shuffles a list.

NumPy
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)
OutputSuccess
Important Notes

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().

Summary

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.