Master NumPy From Scratch

Learn NumPy fundamentals, arrays, indexing, slicing, data types, array operations, broadcasting, mathematical functions, statistics, random numbers, linear algebra, file handling, and practical projects through structured lessons.

COURSE SYLLABUS
1. NumPy Introduction and Installation
Introduction to NumPy NumPy Installation and Setup NumPy Environment and IDE Setup First NumPy Program
2. NumPy Arrays and Array Creation
NumPy Array Fundamentals Array Creation Functions Zeros, Ones and Identity Arrays Range and Linspace Arrays
3. NumPy Array Indexing and Slicing
One-Dimensional Array Indexing Array Slicing Techniques Two-Dimensional Array Indexing Boolean and Fancy Indexing
4. NumPy Data Types and Attributes
NumPy Data Types Array Shape, Size and Dimensions Data Type Conversion and Casting Array Inspection and Attributes
5. NumPy Array Shape and Reshaping
Reshape and Flatten Arrays Transpose and Axis Operations Stacking and Splitting Arrays Expand and Squeeze Dimensions
6. NumPy Array Operations and Broadcasting
Arithmetic Array Operations Comparison and Logical Operations Broadcasting Fundamentals Universal Functions and Vectorization
7. NumPy Mathematical and Statistical Functions
Mathematical Functions Aggregate and Statistical Functions Minimum, Maximum and Percentiles Rounding and Trigonometric Functions
8. NumPy Filtering and Sorting
Array Filtering and Conditions Sorting and Searching Arrays Unique Values and Set Operations Where, Select and Nonzero Functions
9. NumPy Copies and Views
Array Copies and Views Shallow and Deep Copy Concepts Memory Layout and Contiguity Array Iteration and Memory Efficiency
10. NumPy Random Number Generation
Random Generator Fundamentals Random Integers and Sampling Probability Distributions Random Seeds and Simulation
11. NumPy Linear Algebra
Vectors and Matrices Matrix Multiplication and Dot Product Determinants and Matrix Inverse Eigenvalues and Linear Equations
12. NumPy File Input and Output
Importing and Exporting Text Files CSV Data with NumPy Binary Files and NPY Format NPZ Files and Data Persistence
13. NumPy Practical Projects
Student Marks Analysis Project Sales Data Analysis Project Random Simulation Project Image Array Processing Project
14. NumPy Practice and Assessment
NumPy Beginner Practice NumPy Intermediate Exercises NumPy Advanced Challenges Final NumPy Assessment

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.
Important: A simulation estimates probabilities from generated outcomes. For a finite number of trials, experimental results may differ from the theoretical probability.

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.

import numpy as np rng = np.random.default_rng() random_values = rng.random(5) print(random_values)

Example Output

[0.183... 0.742... 0.519... 0.096... 0.861...]

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.

import numpy as np rng = np.random.default_rng(42) tosses = rng.integers(0, 2, size=10) print("Coin toss results:") print(tosses) heads = np.sum(tosses == 1) tails = np.sum(tosses == 0) print("Heads:", heads) print("Tails:", tails)

Example Output

Coin toss results: [0 1 1 0 0 1 0 1 0 0] Heads: 4 Tails: 6

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.

Why use size=10? It requests ten tosses at once instead of requiring a loop to generate each outcome separately.

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.

number_of_tosses = 10000 tosses = rng.integers(0, 2, size=number_of_tosses) heads_count = np.sum(tosses == 1) tails_count = np.sum(tosses == 0) heads_probability = heads_count / number_of_tosses tails_probability = tails_count / number_of_tosses print("Number of tosses:", number_of_tosses) print("Heads count:", heads_count) print("Tails count:", tails_count) print("Estimated probability of heads:", heads_probability) print("Estimated probability of tails:", tails_probability)

Understanding the Calculation

Experimental probability = Event count / Total trials

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.

Remember: For a fair coin, the theoretical probability of Heads is 0.5. A simulation with a finite number of tosses is not guaranteed to produce exactly 50% Heads.

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.

rng = np.random.default_rng(42) trial_sizes = [10, 100, 1000, 10000] for n in trial_sizes: tosses = rng.integers(0, 2, size=n) probability = np.mean(tosses == 1) print( "Trials:", n, "| Estimated heads probability:", round(probability, 4) )

Example Output Format

Trials: 10 | Estimated heads probability: ... Trials: 100 | Estimated heads probability: ... Trials: 1000 | Estimated heads probability: ... Trials: 10000 | Estimated heads probability: ...

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.

rng = np.random.default_rng(42) dice_rolls = rng.integers(1, 7, size=20) print("Dice rolls:") print(dice_rolls) for face in range(1, 7): count = np.sum(dice_rolls == face) print("Face", face, ":", count)

Example Output Format

Dice rolls: [... ... ... ...] Face 1 : ... Face 2 : ... Face 3 : ... Face 4 : ... Face 5 : ... Face 6 : ...

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.

rng = np.random.default_rng(42) number_of_rolls = 10000 dice_rolls = rng.integers(1, 7, size=number_of_rolls) counts = np.bincount(dice_rolls, minlength=7)[1:] probabilities = counts / number_of_rolls print("Face counts:") print(counts) print("\nEstimated probabilities:") print(np.round(probabilities, 4))

Example Output Format

Face counts: [...] Estimated probabilities: [...]

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.

rng = np.random.default_rng(42) number_of_trials = 10000 die_one = rng.integers(1, 7, size=number_of_trials) die_two = rng.integers(1, 7, size=number_of_trials) dice_sums = die_one + die_two print("First five sums:") print(dice_sums[:5]) print("Average sum:", np.mean(dice_sums)) print("Minimum sum:", np.min(dice_sums)) print("Maximum sum:", np.max(dice_sums))

Expected Range of Results

Minimum sum: 2 Maximum sum: 12

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.

rng = np.random.default_rng(42) number_of_trials = 100000 die_one = rng.integers(1, 7, size=number_of_trials) die_two = rng.integers(1, 7, size=number_of_trials) dice_sums = die_one + die_two sum_is_seven = dice_sums == 7 estimated_probability = np.mean(sum_is_seven) print("Trials:", number_of_trials) print("Number of sums equal to 7:", np.sum(sum_is_seven)) print("Estimated probability:", round(estimated_probability, 4))

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.

NumPy shortcut: The mean of a Boolean array treats True as 1 and False as 0. Therefore, 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.

rng = np.random.default_rng(42) students = np.array([ "Samadhan", "Pradnya", "Samiksha", "Student04", "Student05", "Student06", "Student07", "Student08", "Student09", "Student10", "Student11", "Student12", "Student13", "Student14", "Student15", "Student16", "Student17", "Student18", "Student19", "Student20", "Student21", "Student22", "Student23", "Student24", "Student25", "Student26", "Student27", "Student28", "Student29", "Student30" ]) sample = rng.choice(students, size=5, replace=False) print("Selected sample:") print(sample)

Setting replace=False prevents the same student from being selected more than once in the sample. If repeated selection is permitted, use replace=True.

Sampling note: Random sampling is useful for learning and experimentation. Real studies may need additional sampling rules to ensure the sample represents the population appropriately.

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.

rng = np.random.default_rng(42) sample_values = rng.normal( loc=50, scale=10, size=1000 ) print("Sample mean:", round(np.mean(sample_values), 2)) print("Sample standard deviation:", round(np.std(sample_values), 2)) print("Minimum:", round(np.min(sample_values), 2)) print("Maximum:", round(np.max(sample_values), 2))

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.

rng = np.random.default_rng(42) values = rng.normal(100, 15, size=5000) mean_value = np.mean(values) median_value = np.median(values) std_value = np.std(values) minimum_value = np.min(values) maximum_value = np.max(values) print("Mean:", round(mean_value, 2)) print("Median:", round(median_value, 2)) print("Standard deviation:", round(std_value, 2)) print("Minimum:", round(minimum_value, 2)) print("Maximum:", round(maximum_value, 2))

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.

rng = np.random.default_rng(42) tosses = rng.integers(0, 2, size=10000) heads_count = np.sum(tosses == 1) tails_count = np.sum(tosses == 0) np.savez_compressed( "random_simulation_results.npz", tosses=tosses, heads_count=heads_count, tails_count=tails_count ) print("Simulation results saved.") with np.load("random_simulation_results.npz") as data: loaded_tosses = data["tosses"] loaded_heads = data["heads_count"] loaded_tails = data["tails_count"] print("Loaded toss count:", loaded_tosses.size) print("Loaded heads:", int(loaded_heads)) print("Loaded tails:", int(loaded_tails))

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.

import numpy as np # Create a reproducible random generator rng = np.random.default_rng(42) # 1. Coin toss simulation number_of_tosses = 10000 tosses = rng.integers(0, 2, size=number_of_tosses) heads_count = np.sum(tosses == 1) tails_count = np.sum(tosses == 0) heads_probability = heads_count / number_of_tosses tails_probability = tails_count / number_of_tosses print("COIN TOSS SIMULATION") print("Total tosses:", number_of_tosses) print("Heads:", heads_count) print("Tails:", tails_count) print("Estimated heads probability:", round(heads_probability, 4)) print("Estimated tails probability:", round(tails_probability, 4)) # 2. Dice roll simulation number_of_rolls = 10000 dice_rolls = rng.integers(1, 7, size=number_of_rolls) dice_counts = np.bincount(dice_rolls, minlength=7)[1:] dice_probabilities = dice_counts / number_of_rolls print("\nDICE SIMULATION") print("Total rolls:", number_of_rolls) print("Face counts:", dice_counts) print("Face probabilities:", np.round(dice_probabilities, 4)) # 3. Simulate the sum of two dice die_one = rng.integers(1, 7, size=number_of_rolls) die_two = rng.integers(1, 7, size=number_of_rolls) dice_sums = die_one + die_two sum_seven_probability = np.mean(dice_sums == 7) print("\nTWO-DICE SIMULATION") print("Average sum:", round(np.mean(dice_sums), 3)) print("Probability of sum 7:", round(sum_seven_probability, 4)) # 4. Save results np.savez_compressed( "random_simulation_results.npz", tosses=tosses, dice_rolls=dice_rolls, dice_sums=dice_sums, dice_counts=dice_counts, dice_probabilities=dice_probabilities ) print("\nSimulation results saved successfully.")

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

  1. Simulate 100 coin tosses and calculate the percentage of Heads.
  2. Simulate 50 dice rolls and count how many times each face appears.
  3. Estimate the probability of rolling a number greater than 4.
  4. Simulate two dice and estimate the probability of getting a sum of 8.
  5. Compare the estimated Heads probability for 100, 1,000, and 10,000 tosses.
  6. Select 10 unique students from a population using random sampling.
  7. Generate 2,000 normally distributed values and calculate their mean.
  8. Save dice outcomes and counts in an NPZ archive and load them again.
  9. 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.