ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)

Set your Publisher ID in src/config/ads.ts to display live ads.

NumPy Tutorial• 6 min read

Random Sampling & Probability Distributions

The modern np.random.default_rng() API, normal distributions, and seeds

NumPy generates pseudo-random numbers and statistical distributions using high-speed bit generators like PCG64.

The Modern default_rng Generator

Legacy API: np.random.seed(42) and np.random.rand() are deprecated for new code.

Modern API: Create an isolated generator using rng = np.random.default_rng(seed=42). This provides superior statistical properties and thread safety.

rng.normal(loc=0.0, scale=1.0, size=(1000,)): Draws samples from a Gaussian (Normal) distribution.

rng.integers(low, high, size): Generates uniform discrete random integers.

rng.choice(arr, size, replace=False): Randomly samples elements from an array with or without replacement.

Generating Synthetic Feature Distributions
import numpy as np

# Seeded generator for 100% reproducible experiments
rng = np.random.default_rng(seed=42)

# Generate 5 simulated customer ages: Mean 35, Std Dev 8
ages = rng.normal(loc=35, scale=8, size=5).astype(int)
print("Simulated customer ages:", ages)

# Random train/test split sampling without replacement
indices = np.arange(10)
train_idx = rng.choice(indices, size=7, replace=False)
print("Sampled training indices:", train_idx)
default_rng ensures reproducibility across machine learning experiments.
ADVERTISEMENT
Google AdSense Slot (inContentBanner)

Set your Publisher ID in src/config/ads.ts to display live ads.

Test Yourself With Exercise

+15 XP

What is the recommended modern way to generate random numbers in NumPy?