01 / 20

Computer
Simulations

Explore how computational models let us test hypotheses, predict outcomes, and study complex systems that would be impossible, dangerous, or impractical to observe in real life.

AP Computer Science Principles

What Is a Simulation?

A simulation is an abstraction of a complex natural or artificial phenomenon, implemented as a computer program. It uses mathematical models and algorithms to mimic real-world behavior so we can observe, analyze, and predict outcomes.

Abstraction
Simulations simplify reality by including only the most relevant variables and rules.
Computation
Algorithms execute thousands of iterations in seconds, far faster than real time.
Prediction
Results help us forecast outcomes without conducting the actual experiment.

Why Simulations Matter

Some scenarios are too expensive, dangerous, or time-consuming to test in reality. Simulations give us a safe, repeatable way to explore "what if" questions.

1
Safety: Crash-testing cars or modeling nuclear reactions without risk.
2
Cost: Testing a bridge design digitally before spending millions on materials.
3
Time: Simulating 10,000 years of climate data in hours.
4
Ethics: Studying disease spread without exposing real populations.

Simulations in the Real World

Weather Forecasting
Models use temperature, pressure, and humidity data to predict storms and rainfall patterns.
Flight Simulators
Pilots train on virtual cockpits that replicate turbulence, instruments, and emergency scenarios.
Epidemiology
Disease-spread models (like SIR) help governments plan vaccination and quarantine strategies.

Anatomy of a Simulation

Inputs Parameters, Initial Conditions Model / Algorithm Rules, Equations, Randomness (Repeat N times) Outputs Predictions, Data, Patterns Refine model based on results SIMULATION PIPELINE

Core Principles of Simulations

1
Abstraction: Simulations remove unnecessary details. A traffic simulation may ignore the color of cars but track speed, position, and lane.
2
Fidelity Trade-offs: More detail means more accuracy but requires more computing power and time.
3
Randomness: Many simulations use pseudo-random numbers to model unpredictable real-world behavior.
4
Repetition: Running many trials reveals statistical patterns. One run shows a single outcome; thousands show a distribution.

Simulation vs. Experiment vs. Calculation

Simulation Experiment Calculation
Approach Computer model of reality Physical test in real world Exact math formula
Randomness Often included Inherent in nature None (deterministic)
Cost / Risk Low High Very low
Accuracy Approximate Most accurate Exact (if model correct)
Best For Complex systems Validating models Simple, solvable problems

The Role of Randomness

Many simulations incorporate pseudo-random number generators to model uncertainty. This is essential when the real system involves chance: dice rolls, weather fluctuations, genetic mutations, or stock prices.

Deterministic
Same inputs always produce the same outputs. Example: calculating projectile trajectory in a vacuum.
Stochastic
Outputs vary each run due to random elements. Example: simulating coin flips or disease transmission.

How to Build a Simulation

1
Define the question: What are you trying to learn or predict?
2
Identify variables: Choose which factors to include and which to abstract away.
3
Build the model: Write the rules, equations, and/or random processes that govern behavior.
4
Run many trials: Execute the simulation hundreds or thousands of times to gather data.
5
Analyze results: Look for patterns, averages, distributions, and outliers.
6
Refine the model: Adjust assumptions and re-run if results seem unrealistic.

Birthday-match simulation

This separate worked question comes from the related lesson.

A student writes the following simulation to estimate the probability that two people in a group of 30 share the same birthday. The simulation uses the simplification that there are exactly 365 days in a year and all birthdays are equally likely. matches ← 0 REPEAT 10000 TIMES { birthdays ← [] foundMatch ← false REPEAT 30 TIMES { day ← RANDOM(1, 365) IF (day IS IN birthdays) { foundMatch ← true } APPEND(birthdays, day) } IF (foundMatch) { matches ← matches + 1 } } probability ← matches / 10000 DISPLAY(probability) (a) The theoretical probability that at least two people in a group of 30 share a birthday is approximately 0.706. Explain why the simulation's output might differ from this value on any single execution. (b) Describe one simplification (abstraction) made in this simulation and explain how it could affect the accuracy of the result. (c) A classmate suggests that running the outer loop only 10 times instead of 10,000 would be sufficient. Evaluate this claim. (d) Propose a specific modification to the simulation that would allow the student to investigate how the probability changes as the group size increases from 2 to 50.

Show answer and explanation

Rubric (4 points): Point 1 (Part a): The student explains that the simulation uses random number generation (RANDOM(1, 365)), which introduces variability. Each execution generates different random birthdays, so the proportion of matching trials will fluctuate around the theoretical value. With 10,000 trials, the result will be close to 0.706 but unlikely to be exactly 0.706 due to the inherent randomness of the sampling process. (1 point) Point 2 (Part b): The student identifies a valid abstraction, such as: the simulation assumes all 365 days are equally likely, but in reality birthdays are not uniformly distributed (more births occur in certain months). This simplification could slightly underestimate the true probability because clustering of real birthdays makes matches somewhat more likely. Alternatively, the student could note the omission of leap years (Feb 29), which slightly affects the calculation. (1 point) Point 3 (Part c): The student correctly evaluates the claim as flawed. With only 10 trials, the estimated probability could vary wildly — for example, anywhere from 0.4 to 1.0 — because 10 samples provide an extremely small dataset from which to draw conclusions. The law of large numbers dictates that a larger number of trials produces a more stable and accurate estimate. The original 10,000 trials is a far more appropriate sample size for producing a reliable probability estimate. (1 point) Point 4 (Part d): The student proposes a concrete modification such as: wrap the entire simulation in an outer loop where a variable groupSize iterates from 2 to 50. For each value of groupSize, run 10,000 trials (replacing the hardcoded 30 with groupSize in the inner REPEAT loop), compute the estimated probability, and store or display the result. This produces a list or graph of probabilities for each group size, revealing how match probability increases with group size. The student must describe both changing the group size variable and collecting/displaying results for each size to earn this point. (1 point)

A group of 30 birthday tokens includes repeated days 15 and 42, so this group counts as one success. The no-match companion is a separate group. The probability is about 0.7063; no measured 10,000-trial outcome is asserted.
A group of 30 birthday tokens includes repeated days 15 and 42, so this group counts as one success. The no-match companion is a separate group. The probability is about 0.7063; no measured 10,000-trial outcome is asserted.
A contrasting group with no shared birthday.
A contrasting group with no shared birthday.

Example: Coin Flip Simulation

Question: If you flip a fair coin 1,000 times, how close to \(50\%\) heads will you get?

import random

# Simulate 1000 coin flips
heads = 0
for i in range(1000):
    if random.random() < 0.5:
        heads = heads + 1

print("Heads:", heads, "/ 1000")

Example: Dice Sum Distribution

Question: What is the most common sum when rolling two six-sided dice?

Frequency (%) Sum of Two Dice 2 2.8 3 5.6 4 8.3 5 11.1 6 13.9 7 16.7 8 13.9 9 11.1 10 8.3 11 5.6 12 2.8

Example: Disease Spread Model

An epidemiology simulation might model how a disease spreads through a population using the SIR model: Susceptible, Infected, Recovered.

Susceptible Can catch disease infection rate Infected Has the disease recovery rate Recovered Now immune Each time step, random interactions determine who gets infected or recovers.

Limitations of Simulations

1
Simplifications: Abstraction means some real-world factors are left out, which can make results inaccurate.
2
Bias in design: The programmer's assumptions about rules and variables shape the results.
3
Not proof: A simulation can suggest a likely outcome, but it does not prove that outcome will happen in reality.
4
Computational limits: Extremely complex systems (like global climate) require immense computing power even with simplifications.

The model city leaves some of the real street outside

A miniature city occupies a table beside the real streets it represents.More simulation trials reduce random variation in an estimate. They do not repair a model that leaves out an important part of the real system.

Precision does not remove model bias

Three groups of replicate estimates become narrower around 8 minutes while a separate validation marker remains at 12 minutes.Suppose replicate simulation means remain centered at 8 minutes while the validation target is 12 minutes. Their standard error, 4/√N, shrinks with more trials, but the 4-minute discrepancy remains.

Common Mistakes

✕ Confusing Simulation with Calculation
A simulation models complex behavior using repeated trials and randomness. A calculation applies a formula directly for an exact answer.
✕ Thinking One Run Is Enough
A single simulation run shows one possible outcome. You need many runs to see the full distribution of results.
✕ Ignoring Abstraction Trade-offs
Leaving out a critical variable (like wind in a flight simulation) can invalidate results entirely. Always consider what was simplified.

Summary: Key Concepts

Concept What to Remember
Simulation A computer model that mimics real-world behavior using abstraction
Abstraction Simplifying reality by keeping only relevant variables
Randomness Pseudo-random numbers model unpredictability in stochastic simulations
Repetition Many trials needed to see patterns; one run is not sufficient
Limitations Results are approximate: only as good as the model's assumptions
Not a Proof Simulations suggest outcomes but cannot guarantee real-world results

Question 1 of 5

A researcher wants to study how a wildfire spreads across different terrain. Which of the following best explains why a simulation would be preferred over an experiment?

Question 2 of 5

A simulation of coin flips produces different results each time it is run. Which of the following best explains why?

Question 3 of 5

A student runs a disease-spread simulation once and concludes that exactly \(47\%\) of the population will be infected. What is the primary flaw in this conclusion?

Question 4 of 5

Which of the following is an example of abstraction in a traffic simulation?

Question 5 of 5

A programmer builds a simulation to predict election results but forgets to account for voter turnout differences across age groups. Which limitation does this best illustrate?