Objectives

  1. Understand how computers can be used to represent real-world phenomena or outcomes
  2. Compare simulations with real-world contexts.
  3. Implement code to mimic real world situations, problems, or phenomena.

What are simulations by College Board definition?

  • Simulations are programs that mimic more complex objects or phenomena from the real world
    • Purposes include drawing inferences without the consequences of the real world
  • Simulations use varying sets of values to reflect the hypothetical state of a real phenomenon
  • Often, when developing a simulation, it is necessary to remove specific problems or simplify aspects
    • Simulations can often contain bias based on which details or real-world elements were included/excluded
  • Simulations allow the formulation of predictions under consideration
  • Variability and randomness of the world is considered using random number generators
  • Examples: rolling dice, spinners, molecular models, analyze chemicals/reactions...

Analyzing an Example: Air-Traffic Simulator

  • Say we want to find out what the optimal number of aircrafts that can be in the air in one area is.
  • A simulation allows us to explore this question without real world contraints of money, time, safety
    • Unfortunately we can't just fly 67 planes all at once and see what happens
  • Since the simulation won't be able to take all variables into control, it may have a bias towards one answer
  • Will not always have the same result

Functions we often need (python)

import random # a module that defines a series of functions for generating or manipulating random integers
random.choice() #returns a randomly selected element from the specified sequence
random.choice(mylist) # returns random value from list
random.randint(0,10) #randomly selects an integer from given range; range in this case is from 0 to 10
random.random() #will generate a random float between 0.0 to 1.

Functions we often need (js)

// Math.random(); returns a random number
// Math.floor(Math.random() * 10); // Returns a random integer from 0 to 9:

College Board Question 1

Question: The following code simulates the feeding of 4 fish in an aquarium while the owner is on a 5-day trip:

numFish ← 4

foodPerDay ← 20

foodLeft ← 160

daysStarving ← 0

    REPEAT 5 TIMES {

    foodConsumed ← numFish * foodPerDay

    foodLeft ← foodLeft - foodConsumed

    IF (foodLeft < 0) {

    daysStarving ← daysStarving + 1

    }

}

  • This simulation simplifies a real-world scenario into something that can be modeled in code and executed on a computer.
  • Summarize how the code works:

The numFish is intialized as 4 because there are 4 fish. Each day, the fish needs to be fed 20 of it's food. The foodConsumed is set to the number of fish times the amount of food, showing the total amount of food the fish consume in a day. The foodLeft keeps track of the amount of food left over, by subtracting the total amount of food used in the day. Once this value dips below 0, the program counts how many days the fish have had no food.

Examples

Card Flip

import random

cards = ["Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"] 
suits = ["Diamonds", "Hearts", "Spades", "Clubs"]

print(random.choice(cards) + " of " + random.choice(suits))
Jack of Hearts

Coin Flip

import random

def coinflip():         #def function 
    randomflip = random.randint(0, 0) #picks 0 every time, making the coin always land on heads (weighted coin)
    if randomflip == 0: #assigning 0 to be heads--> if 0 is chosen then it will print, "Heads"
        print("Heads")
    else:
        if randomflip == 1: #assigning 1 to be tails--> if 1 is chosen then it will print, "Tails"
            print("Tails")

#Tossing the coin 5 times:
t1 = coinflip()
t2 = coinflip()
t3 = coinflip()
t4 = coinflip()
t5 = coinflip()
Heads
Heads
Heads
Heads
Heads

Your turn: Change the code to make it simulate the flipping of a weighted coin. DONE

Adding images (in Python)

  • Add a heads and tails images into your images directory with the correct names and run the code below
import random

# importing Image class from PIL package
from PIL import Image
 
# creating a object
im = Image.open(r"images/heads.jpeg")
image = Image.open(r"images/tales.jpg")

i=random.randint(0,1)

if i == 1:
    print("heads")
    display(im)

else:
    print("tails")
    display(image)
tails

In order to display an image in python, we can use the PIL package we previously learned about.

Spin the Wheel

import random
from PIL import Image
import matplotlib.pyplot as plt

def display(image):
    plt.imshow(image)
    plt.axis('off')
    plt.show()

print("Spin the wheel!")
print("----------------------------------")

imr = Image.open(r"images/red.png")
imb = Image.open(r"images/blue.png")

n = 300
blue = 0
red = 0
 
for i in range(n):
    spin = random.randint(1,2)
    if spin == 1: # head
        blue = blue + 1
    else:         # tail
        red = red + 1

if red > blue:
    display(imr)

if red < blue:
    display(imb)
 
print('Number of blue:', blue)
print('Number of red:', red)
Spin the wheel!
----------------------------------
Number of blue: 141
Number of red: 159

Your turn: Add a visual to the simulation!

Population Growth and Plots

import random

totalPopulation = 50 
growthFactor = 1.00005
dayCount = 0 #Every 2 months the population is reported

while totalPopulation < 1000000:
    totalPopulation *= growthFactor
    #Every 56th day, population is reported
    dayCount += 1
    if dayCount == 56: 
        dayCount = 0
        print(totalPopulation)

Here we initialize the total population to be 50, then set the growth factor as 1.00005 (.005 percent change). It will print the population every 56th day until it reaches one million. It multiplies the current population by the growth factor in each iteration, and increments the day count. When the day count reaches 56, it prints the current population and resets the day count to 0.

Note! This simulation assumes that the growth factor remains constant as time progresses, which may not be a realistic assumption in real-world scenarios.

import matplotlib.pyplot as plt

# Define the initial population and growth rate
population = 100
growth_rate = 0.05

# Define the number of years to simulate
num_years = 50

# Create lists to store the population and year values
populations = [population]
years = [0]

# Simulate population growth for the specified number of years
for year in range(1, num_years+1):
    # Calculate the new population size
    new_population = population + (growth_rate * population)
    # Update the population and year lists
    populations.append(new_population)
    years.append(year)
    # Set the new population as the current population for the next iteration
    population = new_population
    
# Plot the population growth over time
plt.plot(years, populations)
plt.xlabel('Year')
plt.ylabel('Population')
plt.title('Population Growth Simulation')
plt.show()

If we create quantative data, we can plot it using the Matplotlib library.

Example on how simplification can cause bias

import random

beak =  ["small-beak", "long-beak", "medium-beak"],
wing = ["small-wings", "large-wings", "medium-wings"],
height = ["short", "tall","medium"]


naturaldisaster = ["flood", "drought", "fire", "hurricane", "dustbowl"]


print("When a" , random.choice(naturaldisaster) , "hit",  random.choice(height), "birds died") 
When a drought hit medium birds died

How does this simulation have bias?

It makes a generalization that is not based on previous data, nor does it account for the true proportion of the type of bird. Because it is completey random, it doesnt mimic the real world.

JS examples

Hacks

  • Answer all questions and prompts in the notes (0.2)
  • Create a simulation

    1. Create a simulation that uses iteration and some form of data collection (list, dictionary...) (0.4)

      • try creating quantative data and using the Matplotlib library to display said data
      • Comment and describe function of each parts
      • How does your simulation help solve/mimic a real world problem?

        It helps to determine how many years the user's car will last, based on the approximation of how many miles it can drive before it breaks down.

      • Is there any bias in your simulation? Meaning, are there any discrepancies between your program and the real event?

        Yes, it assumes that the user will drive 13,500 miles a year. This is just an approximation, and will likely vary based on the needs of the user.

import matplotlib.pyplot as plt # allows data to be displayed visually

annualMiles = 13500 # amount of miles Americans drive each year
breakPoint = int(input("How many miles can your car drive before breaking down?")) # amount of miles a well kept car will last for
milesSF = 0 # initial miles
yearsDrive = 0 # initial year amount

years = []
miles = []

while milesSF < breakPoint: # while amount of miles is less than 300000
    yearsDrive += 1 # each additional year
    milesSF = annualMiles * yearsDrive # every year, 13500 more miles driven
    # display data
    print("Year:", yearsDrive)
    print("Miles Driven:", milesSF)
    print("----------------------")

    years.append(yearsDrive)
    miles.append(milesSF)

# plot data
plt.plot(years, miles)
plt.xlabel('Years Driven')
plt.ylabel('Miles Driven')
plt.title('Mileage of Average Car')
plt.show()
Year: 1
Miles Driven: 13500
----------------------
Year: 2
Miles Driven: 27000
----------------------
Year: 3
Miles Driven: 40500
----------------------
Year: 4
Miles Driven: 54000
----------------------
Year: 5
Miles Driven: 67500
----------------------
Year: 6
Miles Driven: 81000
----------------------
Year: 7
Miles Driven: 94500
----------------------
Year: 8
Miles Driven: 108000
----------------------
Year: 9
Miles Driven: 121500
----------------------
Year: 10
Miles Driven: 135000
----------------------
Year: 11
Miles Driven: 148500
----------------------
Year: 12
Miles Driven: 162000
----------------------
Year: 13
Miles Driven: 175500
----------------------
Year: 14
Miles Driven: 189000
----------------------
Year: 15
Miles Driven: 202500
----------------------
Year: 16
Miles Driven: 216000
----------------------
Year: 17
Miles Driven: 229500
----------------------
Year: 18
Miles Driven: 243000
----------------------
Year: 19
Miles Driven: 256500
----------------------
Year: 20
Miles Driven: 270000
----------------------
Year: 21
Miles Driven: 283500
----------------------
Year: 22
Miles Driven: 297000
----------------------
Year: 23
Miles Driven: 310500
----------------------
  1. A and B

  2. A

  3. A

  4. D

  5. B and C

  6. C

  • Bonus: take a real world event and make a pseudocode representation or pseudocode on a flowchart of how you would make a simulation for it (up to +0.1 bonus)
from PIL import Image
 
Image.open(r"images/oceanacid.png")