Tests, simulations, and demonstrations often need synthetic values with known shapes and limits. A single NumPy random generator can supply several kinds of arrays without hand-writing sample data.
The np.random.default_rng() function creates a Generator whose methods return ordinary ndarray objects. Each method accepts size, and a tuple such as (2, 3) produces two rows and three columns.
A fixed seed supports repeatable verification in tests and documentation, while omitting the seed draws initial entropy from the operating system. NumPy random generators are intended for modeling and simulation rather than passwords, keys, or other cryptographic values.
Related: Seed a random generator
Related: Calculate a histogram
Related: Calculate statistics
Steps to generate random arrays with NumPy:
- Create random-array-generate.py with NumPy and a seeded random generator.
- random-array-generate.py
import numpy as np rng = np.random.default_rng(seed=2026)
- Add floating-point, bounded-integer, and normal-distribution draws after the generator declaration.
uniform = rng.random(size=(2, 3)) integers = rng.integers(low=1, high=10, size=(2, 3)) normal = rng.normal(loc=100.0, scale=5.0, size=(2, 3))
random() draws floats from [0.0, 1.0). integers() includes low and excludes high by default, so this array contains values from 1 through 9.
- Append computed shape and range checks beneath the array declarations.
shape_checks = ( uniform.shape == (2, 3) and integers.shape == (2, 3) and normal.shape == (2, 3) ) uniform_range = ((uniform >= 0.0) & (uniform < 1.0)).all() integer_range = ((integers >= 1) & (integers < 10)).all()
- Append array output and fail-capable assertions beneath the computed checks.
print("uniform:") print(np.round(uniform, 3)) print("integers:") print(integers) print("normal:") print(np.round(normal, 3)) print("shapes:", uniform.shape, integers.shape, normal.shape) print("shape checks passed:", shape_checks) print("uniform range passed:", bool(uniform_range)) print("integer range passed:", bool(integer_range)) assert shape_checks assert uniform_range assert integer_range
- Run the completed random-array script.
$ python3 random-array-generate.py uniform: [[0.179 0.64 0.467] [0.371 0.355 0.791]] integers: [[7 9 7] [2 8 6]] normal: [[ 98.87 103.6 102.574] [ 99.679 99.573 100.805]] shapes: (2, 3) (2, 3) (2, 3) shape checks passed: True uniform range passed: True integer range passed: True
The three True results are computed from the generated arrays. A wrong shape or an out-of-range value makes the corresponding assertion stop the script.
Mohd Shakir Zakaria is a cloud architect with deep roots in software development and open-source advocacy. Certified in AWS, Red Hat, VMware, ITIL, and Linux, he specializes in designing and managing robust cloud and on-premises infrastructures.