Unit 6: Simulations · Creating simulations

Article

Designing a simulation step by step

8 min read

The school canteen has one till. At lunch, will the queue reach the door? You cannot test 500 lunchtimes, and you do not want to stand in a queue to find out. So you build a simulation. Designers follow the same steps every time. You will learn them by building a canteen simulation.

Step 1: Decide what to include

A real canteen has thousands of details: the food, the weather, who stands next to whom, how tired the cook is. A simulation cannot hold them all, and it should not try. Abstraction means leaving out details that do not matter, so that the idea is easy to see. Start from your question: "How long does the queue get during a 30-minute lunch?"

Real detailIn the model?Why
Students arrivingYesThey make the queue longer
The till serving a studentYesIt makes the queue shorter
What each student buysNoIts only effect is how fast the till works, so one number can stand for it
A rush of students when the bell ringsNoLeft out to keep it simple. This makes the model less realistic, so it is a limit

Check your understanding

A simulation estimates how long people wait at a bus stop. Which detail is the best one to leave out?

Step 2: Choose variables and settings

Split what the program holds into two groups.

  • Variables that change during a run: queue (students waiting) and longest (the longest queue so far).
  • Settings that you choose before a run: minutes (how long the lunch is), arriveChance and serveChance (chances, as percentages, for each minute).

Settings become the parameters of a procedure, so you can change them without editing the code inside. Then decide what one time step is. Here it is one minute, with these rules: first a student may join the queue (chance arriveChance%). Then, if someone is waiting, the till may finish with one student (chance serveChance%). Last, we record the queue length.

Step 3: Draw one time step

A flowchart of one minute shows the rules before you write any code.

One minute in the canteen

truefalsetruefalsetruefalseA minute startsRANDOM(1, 100)≤ arriveChance?queue ← queue + 1queue > 0?RANDOM(1, 100)≤ serveChance?queue ← queue - 1If queue > longest,longest ← queueMinute over
Each minute follows one of four paths. The whole simulation repeats this chart once for every minute of lunch.

Step 4: Write it as a procedure

The loop repeats the chart minutes times. The procedure returns longest.

AP pseudocode
PROCEDURE canteen(minutes, arriveChance, serveChance)
{
    queue ← 0
    longest ← 0
    REPEAT minutes TIMES
    {
        IF(RANDOM(1, 100) ≤ arriveChance)
        {
            queue ← queue + 1
        }
        IF(queue > 0)
        {
            IF(RANDOM(1, 100) ≤ serveChance)
            {
                queue ← queue - 1
            }
        }
        IF(queue > longest)
        {
            longest ← queue
        }
    }
    RETURN(longest)
}

Trace canteen(3, 40, 50) with the numbers RANDOM returns, in order: 30, 80, 25, 90, 70, 45.

MinuteArrival roll (≤ 40?)queueServe roll (≤ 50?)queuelongest
130 (yes)180 (no)11
225 (yes)290 (no)22
370 (no)245 (yes)12

The call returns 2. Here is the Python version. Look at the last two lines: they are tests, which the next step explains.

Runs in your browser

Step 5: Test it with answers you know

You cannot check a random result against one right answer. But you can use settings where the answer is certain. If arriveChance is 0, nobody ever arrives, so the result must be 0. If arriveChance is 100 and serveChance is 0, everyone joins and nobody leaves, so after 30 minutes the result must be 30. The second and third lines of output above should always be 0 and 30. Also check that results stay in the possible range: never below 0, never above minutes. A wrong answer here means a bug in the code.

Step 6: Run it many times, then read the results

One lunch is one possible lunch, so run it many times and look at the whole picture. This program keeps each result in a list.

Runs in your browser

Each line shows the setting, the average longest queue and the biggest queue in any run. The results are random, but they follow a pattern. With serveChance 50 the average is about 2.8. With 70 it is about 1.6, so a faster till gives a shorter queue. One lunch with a bad luck streak can reach 8 or more students (about 1 lunch in 100 with serveChance 50). Almost no lunch does with 70.

How a setting changes the results:

ChangeEffect on the queue
arriveChance goes upLonger
serveChance goes upShorter
minutes goes upThe longest queue is usually longer, as there are more minutes for bad luck

Check your understanding

In the canteen simulation, the school buys a faster till. Which change to the settings models this?

The limits of a simulation

A simulation is only as good as what you put into it. These are the limits of this one. The two chances are guesses, so count the real queue for a week and compare. Real students arrive in a rush after the bell, but the model gives every minute the same chance. It has one till, and students never give up and leave. To make it more realistic, add the rush: use a higher arriveChance for the first five minutes. Every change like that adds detail, and each new detail needs a number you must measure or guess.

Common mistakes

  • Putting the settings inside the procedure. Then you must edit the code to try a new setting. Use parameters.
  • Starting queue ← 0 inside the loop. The queue would reset every minute.
  • Trusting one run. One lunch can be unusually good or bad. Use many runs.
  • Believing the model is the real thing. It shows what happens if your assumptions are true, nothing more.
  • Skipping tests. Try settings with a known answer first.

On the exam

You may be asked which details a simulation leaves out (abstraction), which change makes it more realistic (add a detail that really matters), or how a different setting would change the results (faster till, shorter queue). You may be asked what a variable is for, or whether a result "could" happen. Remember: a simulation gives results that can differ every time, and its conclusions are only as good as its assumptions.

Key words

Abstraction: leaving out details that do not matter, so a model stays simple.

Setting: a value you choose before a run, passed in as a parameter.

Time step: one round of the simulation's rules, such as one minute.

Sanity test: running with settings where you already know the answer.

Limit: something a simulation leaves out or guesses, so its results may not match real life.

AP® is a trademark registered by the College Board, which is not affiliated with, and does not endorse, this site. All lessons and questions here are written by JrCodex.