Random Number Generation (The `random` Module) 🎲
6 min read
NumPy: Random Number Generation (The random Module) 🎲
Welcome to the exciting world of random number generation in NumPy! It might sound like something out of a spy movie, but generating random numbers is a fundamental part of many areas in programming, from creating simulations and games to powering complex machine learning algorithms.
The Problem: How can we get a computer, a machine of logic and order, to produce a number that is unpredictable?
The Solution: In most cases, we don't need "truly" random numbers. Instead, we use what are called pseudo-random numbers. These are generated by an algorithm, so they aren't truly random, but they are unpredictable enough for most tasks. Think of it like a deck of cards that has been shuffled so thoroughly that you can't predict the next card.
NumPy's random module is our go-to toolkit for this. It's powerful, fast, and gives us fine-grained control over the "randomness" we create.
The Modern Generator API: np.random.default_rng()
Let's start with the current best practice. For a long time, you might have seen code using np.random.seed(). While it still works, the modern and recommended approach since NumPy version 1.17 is to use np.random.default_rng().
Why the change? The older way used a single, global "random number generator." This could cause problems in complex programs where different parts of the code might unintentionally affect each other's random results.
The new way gives us a fresh, independent generator object. Imagine giving every scientist in a lab their own clean, separate set of beakers and test tubes instead of having them all share from one big, potentially contaminated, set.
Here’s how you get started:
import numpy as np
# Create a new random number generator instance
rng = np.random.default_rng()
# Now, use methods on the 'rng' object to get random numbers
random_float = rng.random()
print(random_float)For Reproducibility: A key concept in data science and research is reproducibility. If you're running an experiment, you want to be able to get the exact same "random" numbers again. This is where a "seed" comes in. A seed is the starting point for the random number generating algorithm.
With default_rng(), you provide the seed when you create the generator:
# Create a generator with a specific seed
rng = np.random.default_rng(seed=42)
# This will ALWAYS produce the same sequence of numbers
print(rng.random())
print(rng.random())
# If we create another generator with the same seed...
rng2 = np.random.default_rng(seed=42)
# ...it will produce the same numbers in the same order
print(rng2.random())
print(rng2.random())This is incredibly useful for debugging, sharing your work, and ensuring that your results can be verified by others.
Continuous Distributions: Uniform and Normal (Gaussian)
Random numbers aren't always just about picking any number. Often, we want numbers that follow a specific pattern or distribution.
Uniform Distribution
The Idea: Every number within a given range has an equal chance of being picked. Think of a perfect, fair die roll; each number from 1 to 6 has the same probability of appearing.
The rng.uniform() method lets us generate random floating-point numbers in a specified range.
# Create a generator
rng = np.random.default_rng(seed=123)
# Generate a single random float between 0 (inclusive) and 1 (exclusive)
random_float = rng.random() # A convenient shortcut for uniform(0, 1)
print(f"A single random float: {random_float}")
# Generate 5 random floats between 10 and 20
random_array = rng.uniform(low=10, high=20, size=5)
print(f"An array of random floats: {random_array}")
# Generate a 2x3 array of random floats between -1 and 1
random_matrix = rng.uniform(low=-1, high=1, size=(2, 3))
print(f"A matrix of random floats:\n{random_matrix}")Real-world scenario: Simulating the arrival time of a bus that is equally likely to arrive any minute within a 10-minute window.
Normal (Gaussian) Distribution
The Idea: This is the classic "bell curve." Numbers are more likely to be near the average (the center of the bell) and become less likely the farther they are from the average.
Many things in nature follow a normal distribution, like people's heights, measurement errors, and blood pressure.
The rng.normal() method is used for this. It's defined by its mean (loc) and standard deviation (scale).
- Mean (
loc): The center of the distribution. - Standard Deviation (
scale): How spread out the numbers are. A smaller standard deviation means the numbers are tightly clustered around the mean.
rng = np.random.default_rng(seed=456)
# Generate an array of 5 numbers from a normal distribution
# with a mean of 0 and a standard deviation of 1
normal_samples = rng.normal(loc=0, scale=1, size=5)
print(f"Normal distribution samples:\n{normal_samples}")
# Let's simulate student test scores
# Mean score = 75, standard deviation = 10
student_scores = rng.normal(loc=75, scale=10, size=20)
print(f"\nSimulated student scores:\n{student_scores}")Fun Fact: The normal distribution is so common in nature because of something called the Central Limit Theorem. In simple terms, if you have a lot of independent random factors influencing an outcome, that outcome will tend to follow a normal distribution.
Discrete Sampling: Random Integers and choice()
Sometimes we don't want a random float; we need a random whole number.
Random Integers
The Idea: Generating random integers within a specific range.
The rng.integers() method is your tool for this.
rng = np.random.default_rng(seed=789)
# A single random integer between 0 and 9 (exclusive of 10)
random_int = rng.integers(low=0, high=10)
print(f"A random integer: {random_int}")
# An array of 5 random integers between 50 and 100
int_array = rng.integers(low=50, high=100, size=5)
print(f"An array of random integers: {int_array}")
# Simulate rolling a six-sided die 10 times
dice_rolls = rng.integers(low=1, high=7, size=10) # high is exclusive!
print(f"Dice rolls: {dice_rolls}")Note: The high parameter is exclusive, meaning it will not be included in the possible outcomes.
choice()
The Idea: Randomly picking one or more items from a given array.
This is incredibly useful for sampling from a dataset or simulating choices.
rng = np.random.default_rng(seed=101)
options = ['rock', 'paper', 'scissors']
# Choose one option
my_choice = rng.choice(options)
print(f"My choice is: {my_choice}")
# Choose 5 times, with replacement (the same option can be chosen again)
choices = rng.choice(options, size=5, replace=True) # replace=True is the default
print(f"Five choices (with replacement): {choices}")
# Choose 2 times, without replacement (each option can only be chosen once)
unique_choices = rng.choice(options, size=2, replace=False)
print(f"Two unique choices (without replacement): {unique_choices}")You can even assign different probabilities to each choice!
rng = np.random.default_rng(seed=112)
# Rigging the game: make 'rock' more likely
probabilities = [0.6, 0.2, 0.2] # Probabilities for rock, paper, scissors
rigged_choices = rng.choice(options, size=10, p=probabilities)
print(f"Rigged choices: {rigged_choices}")Randomizing Order: shuffle() and permutation()
What if you have a list of items and you just want to mix them up?
shuffle()
The Idea: Shuffles an array in-place. This means it modifies the original array directly and does not return a new one.
rng = np.random.default_rng(seed=131)
my_playlist = np.array(['Song A', 'Song B', 'Song C', 'Song D'])
print(f"Original playlist: {my_playlist}")
rng.shuffle(my_playlist)
print(f"Shuffled playlist: {my_playlist}") # The original array is changedImportant: shuffle modifies the array directly. If you need to keep the original array, make a copy first.
permutation()
The Idea: Returns a new, shuffled copy of an array, or a shuffled range of integers. The original array is left unchanged.
rng = np.random.default_rng(seed=415)
original_order = np.arange(5)
print(f"Original order: {original_order}")
new_order = rng.permutation(original_order)
print(f"New permuted order: {new_order}")
print(f"Original is unchanged: {original_order}")permutation is generally safer if you don't want to accidentally modify your original data.
References for Further Reading
- Official NumPy Documentation:
- Best Practices:
- Tutorials and Examples:
Challenge
You are tasked with simulating a quality control (QC) process for a factory that produces electronic resistors. To ensure the simulation is verifiable and reproducible, you must use a specific seed.
Your task is to perform the following steps in order:
- Create a modern NumPy random number
Generatorinstance and seed it with the integer123. Assign this instance to a variable namedrng. - Simulate a production batch of 1000 resistors. The resistance values (in ohms) should follow a normal (Gaussian) distribution with a mean (
loc) of150.0and a standard deviation (scale) of2.5. Store this batch in a variable namedresistor_batch. - From the
resistor_batch, the QC department randomly selects a sample of 50 resistors for detailed inspection. This sampling must be done without replacement (i.e., each resistor can only be chosen once). Assign the resulting array of 50 resistance values to a variable namedinspected_samples. - To eliminate any potential bias in the testing equipment over time, create a randomized testing schedule. Generate a new array that is a random permutation of the
inspected_samples. Assign this new shuffled array to a variable namedinspection_order, ensuring that the originalinspected_samplesarray is not modified in the process.
Expected result
After running your code, the following variables should be correctly defined:
rng: A NumPyGeneratorobject, initialized usingnp.random.default_rng(seed=123).resistor_batch: A NumPy array with shape(1000,). Its values should be floats generated from a normal distribution withloc=150.0andscale=2.5.inspected_samples: A NumPy array with shape(50,)containing 50 unique values sampled fromresistor_batch.inspection_order: A NumPy array with shape(50,)that is a random permutation ofinspected_samples. Theinspected_samplesarray itself must remain in its original, un-shuffled state.