Last updated

Random Numbers

Definition: NumPy can generate random numbers — essential for simulations, sampling, shuffling data, and machine learning.

Example 1 — common generators

import numpy as np
np.random.seed(1)                  # makes results repeatable
print(np.random.rand(3))           # 3 floats between 0 and 1
print(np.random.randint(1, 7, 5))  # 5 dice rolls (1..6)
print(np.random.normal(0, 1, 3))   # 3 from a normal distribution

Example 2 — pick and shuffle

import numpy as np
np.random.seed(2)
items = np.array(["a", "b", "c", "d"])
print(np.random.choice(items, 2))  # pick 2 at random
np.random.shuffle(items)
print(items)                       # order scrambled

About the seed

np.random.seed(n) fixes the random sequence so you get the same "random" numbers each run — vital for reproducible experiments. Remove it for truly different results each time.

💡 Tip: randint(low, high, size) excludes the high value, so dice are randint(1, 7, n).

Try it Yourself
Output

          
Ad · responsive