Random Seeds and Simulation
Learn how to control random number generation using seeds, reproduce NumPy experiments, create independent random generators, and simulate real-world events using random sampling and Monte Carlo methods. Explore reproducibility, probability estimation, vectorized simulation, and practical numerical experiments with detailed examples.
1. Learning Objectives
By the end of this lesson, you will be able to:
- Understand pseudo-random number generation.
- Explain the purpose of a random seed.
- Create random generators using
np.random.default_rng(). - Generate reproducible random sequences.
- Understand how generator state changes after each call.
- Create separate random generators for different tasks.
- Understand the difference between the modern and legacy random APIs.
- Simulate coin tosses and dice rolls.
- Estimate probabilities using repeated random experiments.
- Apply Monte Carlo simulation to estimate numerical values.
- Use NumPy vectorization for efficient simulation.
2. Introduction to Random Seeds
Random numbers are useful in scientific computing, statistical analysis, machine learning, testing, and simulation. However, some experiments need to produce the same results whenever the code is executed under the same conditions.
A random seed is an initial value used to initialize a pseudo-random number generator. Using a seed allows us to reproduce a generated sequence when we recreate the generator with the same seed and repeat the same operations.
In this example, 42 is the seed. The generator
produces five integers from 1 through 100 because the upper
bound of integers() is exclusive by default.
3. Understanding Pseudo-Random Numbers
Computers commonly generate pseudo-random numbers using mathematical algorithms. These values appear random, but they are produced from an internal generator state.
When a generator is initialized with a particular seed, its starting state is determined by that seed. Each random operation advances the state and generates the next requested values.
The random() method generates floating-point
values in the interval from 0 inclusive to 1 exclusive.
Important Characteristics
- A seed initializes a generator.
- A generator produces values according to its algorithm.
- The generator maintains an internal state.
- Requesting more values advances that state.
- Reinitializing the generator with the same seed can reproduce the sequence.
4. Creating Reproducible Random Sequences
Reproducibility is important when testing programs, comparing algorithms, investigating errors, and verifying numerical experiments. Two generators initialized with the same seed and used with the same sequence of operations produce matching outputs.
Output:
Both generators start with the same seed and perform the same operation. Therefore, the generated arrays match.
5. Comparing Different Seeds
Different seeds generally initialize a random generator to different states. As a result, they usually produce different random sequences.
The generated arrays will generally differ because the generators were initialized differently.
However, different seeds do not guarantee that every generated number will be different. Individual values can match by chance.
6. Understanding Generator State
A random number generator maintains internal state. Each call generally advances the state, so repeated calls on the same generator continue the sequence rather than restarting it.
The first call generates five integers. The second call continues from the generator's updated state and generates the next five integers.
Restarting a Sequence
To start the same sequence again, create a new generator using the same seed.
Output:
Both generators start from the same seed and perform the same operation, so their first batches match.
7. Creating Separate Random Generators
A program may contain multiple experiments. For example, one part of a program may simulate student marks while another part simulates attendance. Separate generators help keep these tasks organized.
The marks generator and attendance generator maintain separate states. Requesting additional attendance values does not advance the marks generator.
Using Separate Generators in a Project
Separate generators make it easier to manage different random processes in the same application.
SeedSequence and supported
generator-spawning techniques to help create separate
random streams.
8. Modern Random API vs Legacy API
NumPy provides a modern random generator interface and
older random functions. For new projects, the recommended
starting point is np.random.default_rng().
| Feature | Modern API | Legacy API |
|---|---|---|
| Initialization | np.random.default_rng(seed) |
np.random.seed(seed) |
| Random generation | rng.random() |
np.random.random() |
| State management | Generator object with its own state | Shared global random state |
| Recommended for new code | Yes | Generally avoid for new code |
Modern Approach
Legacy Approach
The modern approach stores the generator in a variable. You can pass that generator to different functions, making the random state explicit and easier to manage.
9. Introduction to Simulation
Simulation is the process of modeling a situation by generating possible outcomes and analyzing the results. Random simulation is useful when outcomes involve uncertainty or when repeated experiments can help estimate a quantity.
Examples of simulation include:
- Simulating coin tosses.
- Simulating dice rolls.
- Estimating the probability of an event.
- Modeling customer demand or daily sales.
- Generating sample student marks for testing.
- Estimating numerical values through Monte Carlo methods.
The code simulates 20 coin tosses. The resulting counts show the observed number of heads and tails in this particular experiment.
10. Simulating Dice Rolls
A fair six-sided die has six possible outcomes: 1, 2, 3,
4, 5, and 6. We can simulate many rolls using
rng.integers().
The upper bound is 7 because the default upper-bound behavior excludes that value. This makes 1 through 6 the possible outcomes.
With many rolls, the observed frequency of each face will generally approach its theoretical probability of one-sixth. The counts will not necessarily be equal.
11. Estimating Probability Through Simulation
Probability can be estimated by repeating an experiment many times and calculating the proportion of trials in which a particular event occurs.
For a fair die, the theoretical probability of rolling a six is one-sixth. We can estimate this probability using repeated simulated rolls.
The estimated probability is the observed number of sixes divided by the total number of rolls.
The estimate will generally be close to one-sixth when the number of independent trials is large, but it is not guaranteed to equal the theoretical probability exactly.
12. Monte Carlo Simulation
Monte Carlo simulation uses random sampling to estimate numerical quantities. It is especially useful when a direct calculation is difficult or when we want to approximate a result through repeated experiments.
Example: Estimating the Value of Pi
Consider a square whose coordinates range from -1 to 1 on both axes. A circle of radius 1 is centered inside the square. Random points are generated uniformly within the square.
A point lies inside the circle when
x² + y² <= 1. The ratio of the circle's
area to the square's area is π/4. Therefore, the fraction
of sampled points inside the circle can be multiplied by
four to estimate π.
The generated points are checked against the circle condition. The number of points inside the circle is used to calculate the estimate.
13. The Law of Large Numbers
The law of large numbers describes how the average of repeated independent observations tends to approach the expected value under appropriate conditions as the number of observations increases.
For a fair six-sided die, the theoretical expected value is 3.5. We can compare the average obtained from different sample sizes.
The averages will often approach 3.5 as the number of observations increases. However, the average does not have to move closer to 3.5 at every step.
What to Observe
- Small samples can show substantial random variation.
- Larger samples often produce more stable averages.
- The sample average can still differ from the theoretical value.
- Simulation results depend on the generated observations.
14. Simulating Student Marks
Random simulation can be used to create synthetic datasets for testing data analysis programs. Consider three fictional students at CIIT TRANING INSTITUTE: Samadhan, Pradnya, and Samiksha.
We will simulate their marks across four subjects and calculate their total and average marks.
The array has three rows and four columns. Each row represents one student, and each column represents one subject.
The parameter axis=1 calculates a result for
each student across the subjects. The parameter
axis=0 calculates an average for each subject
across the students.
15. Vectorized Random Simulation
Vectorization means performing operations on entire arrays instead of processing every element through a Python loop. NumPy's array-based operations make it convenient to generate and analyze large collections of random values.
Generating Normally Distributed Values
The normal() method generates samples from a
normal distribution. The loc parameter specifies
the distribution mean, and scale specifies
its standard deviation.
The sample mean and sample standard deviation will generally be near the specified parameters, but they will not necessarily match them exactly.
Generating Multiple Experiments
This example creates five experiments, each containing
ten simulated dice rolls. Each row represents one
experiment, and axis=1 calculates the
average of each row.
16. Common Mistakes and Best Practices
Common Mistakes
- Expecting repeated calls on the same generator to restart the sequence.
- Assuming that different seeds guarantee different individual values.
- Forgetting that the upper bound of
integers()is exclusive by default. - Using global random state unnecessarily in new programs.
- Treating simulated results as exact theoretical answers.
- Assuming every larger simulation must produce a more accurate estimate.
- Assuming that two arbitrary seeds automatically guarantee statistically independent streams.
- Using NumPy random generation for security-sensitive tasks.
Best Practices
- Prefer
np.random.default_rng()in new NumPy code. - Use a fixed seed when reproducibility is required.
- Record the seed, sample size, and relevant simulation settings.
- Use separate generators to organize separate tasks.
- Use vectorized operations when they make the simulation clearer and more efficient.
- Choose a sample size appropriate for the problem.
- Interpret simulation estimates as approximations when appropriate.
17. Practice Exercises
- Create two generators with seed 500 and verify that both produce matching arrays of random integers.
- Generate 500 random integers between 1 and 100. Calculate the mean, median, minimum, and maximum.
- Simulate 5,000 coin tosses and calculate the observed proportion of heads.
- Simulate 10,000 dice rolls and calculate the observed frequency of each face.
- Estimate the probability of rolling a six using 100,000 simulated dice rolls.
-
Estimate pi using 250,000 random points and compare
the estimate with
np.pi. - Generate simulated marks for Samadhan, Pradnya, and Samiksha across five subjects. Calculate each student's average.
- Create separate generators for simulated sales and customer counts.
- Run a simulation with different sample sizes and explain how the estimated average changes.
- Explain why a random seed is useful when debugging or testing a numerical program.
Summary
In this lesson, we learned how random seeds initialize
pseudo-random number generators and how NumPy's
np.random.default_rng() provides a modern
approach to random number generation. We explored
reproducible sequences, different seeds, generator
state, and separate generators for different tasks.
We also simulated coin tosses, dice rolls, student marks, and normally distributed values. Monte Carlo simulation demonstrated how random sampling can estimate numerical quantities such as pi and probabilities. The law of large numbers explained why sample averages often approach theoretical expectations as sample sizes grow.
Remember to use a fixed seed when reproducibility is important, prefer the modern random generator API for new code, and interpret simulation results according to their sample size and limitations.