NumPy: Random Numbers

Last updated: 2026-08-26

1. What You'll Learn



2. Story

Alice runs a Monte Carlo simulation for a financial model. She gets different results every time — impossible to debug. Bob shows her: "Use default_rng(42) — the same seed always produces the same sequence. Debug with seed, deploy without." Alice fixes her seed, finds the bug in 5 minutes.



3. The Modern Generator API

(1) Creating a Generator

PYTHON
import numpy as np

# Modern way (recommended)
rng = np.random.default_rng(42)  # seed = 42 for reproducibility

# Old way (legacy)
np.random.seed(42)

(2) Common Distributions

PYTHON
rng = np.random.default_rng(42)

print(rng.random(3))        # 3 uniform [0, 1)
print(rng.normal(0, 1, 3))  # 3 standard normal
print(rng.integers(0, 10, 5))  # 5 integers [0, 10)
print(rng.uniform(0, 10, 3))   # 3 uniform [0, 10)
TEXT 📖 Display only
> **Output:** Run NumPy 2.x in your local Python environment to see the ndarray output. The Piston server does not have NumPy pre-installed — install it locally (`pip install numpy`) and compare. Actual values may vary by NumPy version and random seed.

(3) Random Sampling

PYTHON
rng = np.random.default_rng(42)
data = np.arange(10)

# With replacement
sample = rng.choice(data, size=5, replace=True)

# Without replacement
sample2 = rng.choice(data, size=5, replace=False)

# Shuffle
rng.shuffle(data)  # in-place shuffle
TEXT 📖 Display only
> **Output:** Run NumPy 2.x in your local Python environment to see the ndarray output. The Piston server does not have NumPy pre-installed — install it locally (`pip install numpy`) and compare. Actual values may vary by NumPy version and random seed.

▶ Example: Generating random distributions (Difficulty ⭐)

PYTHON
import numpy as np

rng = np.random.default_rng(42)

uniform = rng.random(5)
normal = rng.normal(0, 1, 5)
integers = rng.integers(1, 100, 5)

print("Uniform [0,1):", uniform)
print("Normal N(0,1):", normal)
print("Integers 1-99:", integers)

Output:

TEXT 📖 Display only
Uniform [0,1): [0.77395605 0.43887844 0.85859792 0.69736803 0.09417735]
Normal N(0,1): [-0.45938412 -0.19865146  0.1113586  -1.00408446  2.02558468]
Integers 1-99: [79 64 66 81 96]

▶ Example: Random sampling with and without replacement (Difficulty ⭐⭐)

PYTHON
import numpy as np

rng = np.random.default_rng(42)
data = np.arange(20)

# With replacement — same element can appear multiple times
with_repl = rng.choice(data, size=10, replace=True)
print("With replacement:", with_repl)

# Without replacement — all elements are unique
without_repl = rng.choice(data, size=10, replace=False)
print("Without replacement:", without_repl)

# Shuffle in-place
rng.shuffle(data)
print("Shuffled data:", data)

Output:

TEXT 📖 Display only
With replacement: [ 6 19  9 12  6 15  0  7  3 14]
Without replacement: [13 10  8 11  5  1  9 16 18  4]
Shuffled data: [ 8  7 13 10 18  3 15  5 14 16  0  9  2  1 11 17 12 19  6  4]

▶ Example: Reproducible sequences with seeds (Difficulty ⭐)

PYTHON
import numpy as np

# Same seed = same sequence
rng1 = np.random.default_rng(123)
rng2 = np.random.default_rng(123)

print("rng1:", rng1.random(4))
print("rng2:", rng2.random(4))

# Different seed = different sequence
rng3 = np.random.default_rng(456)
print("rng3:", rng3.random(4))

Output:

TEXT 📖 Display only
rng1: [0.18701985 0.68208779 0.60135938 0.51034031]
rng2: [0.18701985 0.68208779 0.60135938 0.51034031]
rng3: [0.59831648 0.72572267 0.04819845 0.35980509]

Q Why use default_rng instead of np.random.seed?
A default_rng creates an independent Generator object — you can have multiple independent streams. np.random.seed sets a global seed affecting all code, which is fragile and can cause cross-module interference.
Q How do I get reproducible results?
A Pass a fixed seed: rng = np.random.default_rng(42). The same seed always produces the same sequence. Use different seeds for different runs.
Q What's the difference between random and uniform?
A rng.random(size) returns values in [0, 1). rng.uniform(low, high, size) returns values in [low, high). random is a special case of uniform(0, 1).

❓ FAQ

Q What is the most important thing to remember?
A NumPy operations are vectorized — avoid Python loops for better performance.
Q Where can I learn more?
A Check the official NumPy documentation at numpy.org for detailed references and advanced topics.
Q Does this work with NumPy 2.x?
A Yes — all examples are compatible with NumPy 2.x. Some older APIs (like np.random.seed) are still supported but the modern alternatives are recommended.

📖 Summary



📝 Exercises

  1. Beginner (Difficulty ⭐): Use default_rng(42) to generate 10 random floats, 10 random integers (0-100), and 10 numbers from a normal distribution. Print them.

  2. Intermediate (Difficulty ⭐⭐): Generate 1000 random numbers from a normal distribution. Compute their mean and std. Verify they're approximately 0 and 1.

  3. Advanced (Difficulty ⭐⭐⭐): Use rng.choice with and without replacement to sample 10 items from a dataset of 100. Explain the difference and when you'd use each.

Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏