NumPy's random tools generate arrays filled with random numbers. They're widely used for test data, simulation, sampling, and machine learning initialization. Since random results can differ from one run to the next, set a seed on the random generator if you want reproducible results.
import numpy as np
rng = np.random.default_rng(seed=42)
# Random floats between 0 and 1
floats = rng.random((2, 3))
print("Random floats:
", floats)
# Random integers from 1 to 10
integers = rng.integers(1, 11, size=(3, 3))
print("
Random integers:
", integers)np.random.default_rng(seed=42) builds a random number generator. Since a seed is set, you'll get the same result every time you rerun the code. rng.random((2, 3)) produces a 2x3 array of random floats, and rng.integers(1, 11, size=(3, 3)) produces an array of integers from 1 to 10. 11 is not included.
Random floats: [[0.77395605 0.43887844 0.85859792] [0.69736803 0.09417735 0.97562235]] Random integers: [[8 8 8] [8 6 2] [9 5 6]]Info
For new projects, using np.random.default_rng() is the cleaner choice. In older code you'll still run into np.random.rand() and np.random.randint() as well.