Random Simulation Project Using NumPy
In this practical project, we will use NumPy to simulate random events and estimate probabilities. We will perform coin toss experiments, simulate dice rolls, generate random samples, and analyze the results using statistical functions. This project demonstrates how random number generation can help us model real-world situations without performing every experiment physically.
1. Project Objectives
After completing this project, you will be able to:
- Create a NumPy random number generator.
- Simulate repeated coin tosses.
- Simulate dice rolls and count each outcome.
- Estimate probabilities using experimental results.
- Generate random samples from a population.
- Calculate mean, standard deviation, minimum, and maximum.
- Understand how the number of trials affects estimated probabilities.
- Save simulation data for further analysis.
2. What Is a Random Simulation?
A random simulation uses generated random values to imitate a process or experiment. Instead of tossing a physical coin hundreds of times, we can generate outcomes with NumPy and analyze the results.
Examples of Random Simulations
- Coin tosses to estimate the probability of heads.
- Dice rolls to study the frequency of each face.
- Random customer arrivals for a queueing experiment.
- Random sampling to estimate population statistics.
- Repeated trials to study uncertainty in a process.
3. Create a NumPy Random Generator
NumPy provides np.random.default_rng() to create a random number
generator. Using a dedicated generator is a recommended approach for new code.
Example Output
The exact values will vary each time the program runs because no seed was specified.
The random() method generates floating-point values from 0, inclusive,
to 1, exclusive.
4. Simulate a Coin Toss
A coin has two possible outcomes: Heads and Tails. We can represent Heads as 1 and
Tails as 0. The rng.integers() method can generate values of 0 or 1.
Example Output
The example output illustrates the format of the result. With the seed shown, NumPy's generated values are reproducible within the same compatible random generator implementation.
5. Estimate the Probability of Heads
Experimental probability is calculated by dividing the number of times an event occurs by the total number of trials.
Understanding the Calculation
If 5,020 out of 10,000 tosses are Heads, the estimated probability is
5020 / 10000 = 0.502. The actual result depends on the generated sample.
6. Compare Different Numbers of Tosses
We can compare estimates obtained from increasingly large samples. Larger samples often produce estimates closer to the theoretical probability, although no individual simulation is guaranteed to be closer than every smaller one.
Example Output Format
The exact estimates depend on the generated sequences. Each iteration above consumes the next values from the same random generator, so the samples are generated sequentially.
7. Simulate Dice Rolls
A standard six-sided die has outcomes from 1 through 6. The upper bound in
rng.integers() is exclusive, so we use 7 to include 6.
Example Output Format
Each count indicates how many times a particular face appeared. With only 20 rolls, the counts will not necessarily be equal.
8. Calculate Dice Outcome Frequencies
The np.bincount() function counts occurrences of non-negative integer
values. Since dice faces range from 1 to 6, we can count all faces and ignore the
count at index 0.
Example Output Format
For a fair die, the theoretical probability of each face is \(1/6\), approximately 0.1667. The estimated probability for each face can differ from this value in a finite simulation.
9. Simulate the Sum of Two Dice
When two six-sided dice are rolled, their values can be added together. The minimum possible sum is 2 and the maximum is 12.
Expected Range of Results
The sample average will generally be near 7 for a large number of trials. This is because the expected value of each fair die is 3.5, so the expected sum is 7.
10. Estimate the Probability of a Dice Event
Suppose we want to estimate the probability that the sum of two dice is 7. We can create a Boolean condition and calculate its mean.
There are six equally likely outcomes that produce a sum of 7 out of 36 possible ordered pairs. Therefore, the theoretical probability is \(6/36 = 1/6\). The simulation estimates this probability from the generated trials.
np.mean(condition) calculates the fraction of
trials where the condition is true.
11. Generate Random Samples from a Population
Random sampling selects a subset from a larger population. For example, suppose a class contains 30 students and we want to select five students for a survey.
Setting replace=False prevents the same student from being selected
more than once in the sample. If repeated selection is permitted, use
replace=True.
12. Generate Random Values from a Normal Distribution
NumPy can generate values from common probability distributions. The normal distribution is often used as a model for measurements that cluster around a mean.
The parameter loc is the distribution mean, scale is its
standard deviation, and size is the number of values generated.
The sample statistics will not necessarily equal the specified distribution
parameters exactly.
13. Analyze Simulation Results
NumPy's statistical functions can summarize the simulated values. For example, we can calculate the average, standard deviation, minimum, and maximum of a sample.
These statistics help us understand the center and spread of the simulated data. The minimum and maximum are especially sensitive to the sample size because larger samples provide more opportunities to observe extreme values.
14. Save Simulation Results to an NPZ File
We can save generated outcomes and calculated statistics for later analysis using NumPy's compressed NPZ format.
The with np.load(...) pattern ensures that the archive is closed
automatically when reading is complete.
15. Complete Random Simulation Program
The following program combines a coin toss experiment, dice simulation, probability estimation, and file saving into one runnable script.
Run the script in your Python environment. It prints the simulation statistics
and creates random_simulation_results.npz in the current working
directory.
16. Common Mistakes
Mistake 1: Using the wrong upper bound for dice rolls
rng.integers(1, 6) generates values from 1 through 5. Use
rng.integers(1, 7) to include face 6.
Mistake 2: Expecting exactly equal outcomes
Random experiments can produce unequal counts even when outcomes are equally likely. The counts tend to become more balanced proportionally as the number of trials increases.
Mistake 3: Forgetting that random() excludes 1
rng.random() generates values from 0 inclusive to 1 exclusive.
It does not generate 1 as a possible result.
Mistake 4: Confusing a seed with a fixed result for all code
A fixed seed makes a generator's sequence reproducible when the same compatible generator and sequence of calls are used. Changing the calls or their order can change subsequent results.
Mistake 5: Treating an estimate as an exact probability
A simulated probability is based on observed trials. It can differ from the theoretical probability, especially with small samples.
17. Practice Exercises
- Simulate 100 coin tosses and calculate the percentage of Heads.
- Simulate 50 dice rolls and count how many times each face appears.
- Estimate the probability of rolling a number greater than 4.
- Simulate two dice and estimate the probability of getting a sum of 8.
- Compare the estimated Heads probability for 100, 1,000, and 10,000 tosses.
- Select 10 unique students from a population using random sampling.
- Generate 2,000 normally distributed values and calculate their mean.
- Save dice outcomes and counts in an NPZ archive and load them again.
- Repeat an experiment with a different seed and compare the results.
Summary
In this project, you used NumPy's random generator to simulate coin tosses, dice rolls, two-dice sums, random sampling, and normally distributed values. You calculated experimental probabilities, counted outcomes, and analyzed generated data using statistical functions.
You also learned how sample size affects probability estimates, how to make simulations reproducible with a seed, and how to save simulation arrays using NPZ files. These concepts are useful in probability experiments, statistical modeling, testing, and Monte Carlo simulations.