Random arrays let NumPy code simulate measurements, build repeatable tests, and create synthetic inputs without hand-writing sample data. One generator object can draw floating-point values, bounded integers, and distribution-based samples while returning normal ndarray objects.
np.random.default_rng() creates a Generator, which is the modern NumPy random API. Its methods use size for output shape, so a tuple such as (2, 3) creates a two-row, three-column array.
Use an explicit seed for documentation, tests, and experiments that need the same values on repeated runs. Leave the seed out when each run should draw a new sequence from the operating system's entropy source.
Related: Seed a random generator
Related: Calculate a histogram
Related: Calculate statistics
import numpy as np rng = np.random.default_rng(seed=2026) uniform = rng.random(size=(2, 3)) integers = rng.integers(low=1, high=10, size=(2, 3)) normal = rng.normal(loc=100, scale=5, size=6) print("uniform shape:", uniform.shape) print(np.round(uniform, 3)) print("integers shape:", integers.shape) print(integers) print("normal mean:", round(float(normal.mean()), 2)) print("normal std:", round(float(normal.std(ddof=1)), 2)) shape_checks = ( uniform.shape == (2, 3) and integers.shape == (2, 3) and normal.shape == (6,) ) integer_bounds = ((integers >= 1) & (integers < 10)).all() print("shape checks passed:", shape_checks) print("integer bounds passed:", bool(integer_bounds))
rng.random(size=(2, 3)) returns values in [0.0, 1.0). rng.integers(low=1, high=10, size=(2, 3)) returns integers from 1 through 9 because high is excluded by default.
$ python3 random-array-generate.py uniform shape: (2, 3) [[0.179 0.64 0.467] [0.371 0.355 0.791]] integers shape: (2, 3) [[7 9 7] [2 8 6]] normal mean: 100.85 normal std: 1.87 shape checks passed: True integer bounds passed: True
The pass lines confirm that size produced the requested shapes and that integers() kept every value inside the configured low-inclusive, high-exclusive range. Remove seed=2026 when repeatable output is not required.