np.random basics
NumPy can generate random numbers, which is handy for sample data and simulations.
In this page:
Syntax
rng = np.random.default_rng(seed)
rng.random(size)
rng.integers(low, high, size)
rng.normal(loc, scale, size)
np.random basics
The modern way is np.random.default_rng(seed), which returns a Generator with methods such as random, integers and normal. Setting a seed makes results reproducible. Legacy functions like np.random.rand still work and are covered later.
Note:
Always seed when you want the same numbers every run, such as in tutorials and tests.
Example: np.random basics
import numpy as np
rng = np.random.default_rng(42)
print(rng.random(3).round(3))
print(rng.integers(1, 10, size=5))
# Output:
# [0.774 0.439 0.859]
# [1 7 2 1 5]
Related Topics
Common Mistakes
- Forgetting to seed and getting different output each time
- Mixing legacy and Generator APIs
- Expecting integers() upper bound to be inclusive
Chapter Summary
- default_rng creates a Generator
- Seed for reproducibility
- random gives floats in 0 to 1
- integers excludes the high value
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: