Generate Random Numbers with NumPy
A seeded random generator produces the same pseudorandom sequence, which is useful for examples and repeatable tests.
What is Generate Random Numbers with NumPy?
A seeded random generator produces the same pseudorandom sequence, which is useful for examples and repeatable tests.
Generate reproducible random integers with NumPy's modern Generator API.
When should you use it?
- Perform numerical operations on many values at once.
- Process arrays, matrices, and scientific data efficiently.
- Prepare data for data science and machine learning.
Example code
main.py
import numpy as np
generator = np.random.default_rng(seed=42)
values = generator.integers(low=1, high=11, size=5)
print(values)
Expected output
[1 8 7 5 5]
How it works
Default_rng creates the recommended Generator object. The fixed seed makes this example deterministic across repeated runs.
Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.
Practice exercises
Modify the runnable example with the exercises below to build understanding beyond copying the result.
- Change the input shape and dtype.
- Try negative, floating-point, and missing values.
- Apply the operation to larger multidimensional arrays and measure performance.