P3-M 4/25 Simulations
Creating simulations using pandas and python libraries
- Objectives
- What are simulations by College Board definition?
- Analyzing an Example: Air-Traffic Simulator
- Functions we often need (python)
- Functions we often need (js)
- College Board Question 1
- Examples
- Adding images (in Python)
- Population Growth and Plots
- Example on how simplification can cause bias
- JS examples
What are simulations by College Board definition?
- Simulations are
abstractions
that mimic more complex objects or phenomena from the real world- Purposes include drawing inferences without the
constraints
of the real world
- Purposes include drawing inferences without the
- Simulations use varying sets of values to reflect the
changing
state of a real phenomenon - Often, when developing a simulation, it is necessary to remove specific
details
or simplify aspects- Simulations can often contain
bias
based on which details or real-world elements were included/excluded
- Simulations can often contain
- Simulations allow the formulation of
hyphothesis
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
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.
// Math.random(); returns a random number
// Math.floor(Math.random() * 10); // Returns a random integer from 0 to 9:
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:
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))
import random
def coinflip(): #def function
randomflip = random.randint(0, 1) #picks either 0 or 1 randomly
if randomflip == 0: #assigning 0 to be heads--> if 0 is chosen then it will print, "Heads"
print("Heads")
else:
print("Tails")
#Tossing the coin 5 times:
t1 = coinflip()
t2 = coinflip()
t3 = coinflip()
t4 = coinflip()
t5 = coinflip()
Your turn: Change the code to make it simulate the flipping of a weighted coin.
- 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
head = Image.open(r"images/head.jpeg")
tail = Image.open(r"images/tail.jpeg")
i=random.randint(0,1)
if i == 1:
print("heads")
display(head)
else:
print("tails")
display(tail)
In order to display an image in python, we can use the PIL package we previously learned about.
import random
print("Spin the wheel!")
print("----------------------------------")
n = 5
blue = 0
red = 0
green = 0
RedImg = Image.open(r"images/red.png")
BlueImg = Image.open(r"images/blue.png")
GreenImg = Image.open(r"images/green.png")
for i in range(n):
spin = random.randint(1,3)
if spin == 1: # blue
blue = blue + 1
elif spin == 2: # green
green = green + 1
else: # red
red = red + 1
def red_display():
print('Number of red:', red)
i = 0
while i < red:
display(RedImg)
i = i + 1
def green_display():
print('Number of green:', green)
i = 0
while i < green:
display(GreenImg)
i = i + 1
def blue_display():
print('Number of blue:', blue)
i = 0
while i < blue:
display(BlueImg)
i = i + 1
red_display()
green_display()
blue_display()
Your turn: Add a visual to the simulation!
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.
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")
How does this simulation have bias?
This simulation contains bias because it only includes certain natural disasters, and a limited amount of animals that are affected by it. In order to be a true simulation of the natural disaster, it would have to include every part. However, that would defeat the purpose of a simulation, so most simulations are often somewhat biased.
- Answer all questions and prompts in the notes (0.2)
- Create a simulation
- 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?
- Is there any bias in your simulation? Meaning, are there any discrepancies between your program and the real event?
- Create a simulation that uses iteration and some form of data collection (list, dictionary...) (0.4)
- Answer these simulation questions (0.3)
- 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)
import matplotlib.pyplot as plt
M = 1000 # max capacity of animals that can be carried
a = 2 # initial number of animals at start of simulation
k = 0.005 # logistic growth rate
e = 2.71828 # approximate value of e (not included in python)
t = 100 # time span of simulation
population = [a]
time = [0]
for i in range(1, t+1):
y = M / (1 + ((M / a) - 1) * e ** (-k * i))
population.append(y)
time.append(i)
a = y # new population value is set equal to current population value
plt.plot(time, population)
plt.xlabel('Time in Months')
plt.ylabel('Population')
plt.title('Population Growth w/ Limited Resources')
plt.show()
How does your simulation help solve/mimic a real world problem?
My simulation represents population growth when there are limited resources, which prevents the population from growing indefinitely. It uses logistic growth to do this, which sets a maximum cap on the population
Is there any bias in your simulation? Meaning, are there any discrepancies between your program and the real event?
Yes. The simulation assumes the maximum cap, which can be affected by different factors which may have been unaccounted for. Also, population usually does not increase in a smooth graph, but fluctuates, due to environmental factors.
Simulation Questions
1: A theme park wants to create a simulation to determine how long it should expect the wait time at its most popular ride. Which of the following characteristics for the virtual patrons would be most useful? Select two answers
A and B: Ride preference and Walking preference are more likely to be useful. They both affect how many people are going to show up to wait for a ride. Food preferences and ticket type do not affect which rides patrons will choose in the moment as much
2: A programmer has created a program that models the growth of foxes and rabbits. Which of the following potential aspects of the simulation does NOT need to be implemented?
A: grass. Grass is mostly everywhere, so having enough grass would not be a problem for rabbits, and therefore not affect their population as much as the other options
3: The heavy use of chemicals called chlorofluorocarbons (CFCs) has caused damage to the Earth’s ozone layer, creating a noticeable hole over Antarctica. A scientist created a simulation of the hole in the layer using a computer, which models the growth of the hole over many years. Which of the following could be useful information that the simulation could produce?
B: The exact size of the hole can be determined through the simulation, since the simulation is measuring the growth of the hole specifically
4: Suppose that an environmentalist wanted to understand the spread of invasive species. What would be a benefit of doing this with a simulation, rather than in real life?
D: The simulation would be more effective in modeling species, it would be more versatile, and even more efficient. Having a virtual simulation means factors of the model can be changed quickly to test differnet circumstances
5: A program is being created to simulate the growth of a brain-based on randomly determined environmental factors. The developer plans to add a feature that lets the user quickly run several hundred simulations with any number of factors kept constant. Why would this be useful? Select two answers.
B and D: While having a simulation keep all but one variable the same, it becomes a lot easier to test the effects of that single variable. And it is a lot easier to control all variables in a virtual simulation. The simulations would also be more detailed because of the fact that several hundred are being ran
6: Which of the following statements describes a limitation of using a computer simulation to model a real-world object or system?
C: It is impossible (and impractical) to account for literally everything in a simulation, so they often generalize things in order to gain an estimate of how the real life situation would work