Thuta Learning
AdvancedData & Databasesintermediate

Random Numbers

Relax. We'll talk through this in plain words — no textbook voice.

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.

python
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.

You should see
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.

Easy traps

  • In rng.integers(1, 11), the high value 11 is not included. It's written as 11 because you want numbers from 1 to 10.

Exercise

You can use random arrays to test things like user behavior simulation, lottery-style test data, fake sales numbers, or A/B testing sample data.

You'll know it worked when: