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
hypothesis
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:
The constants tells us that there are 4 fish which eat 20 pieces of food a day and that there are 160 pieces of food left. And the rest of the code iterates the sequence 5 times and if the food ever becomes less than 0 it shows the number of days the fish starves.
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, 2) #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")
elif randomflip == 1: ## When I was using if randomflip == 0 or 1 the result was heads all the time so I changed it to this
print("Heads")
else:
if randomflip == 2: #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()
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
im = Image.open(p"images/heads.png")
image = Image.open(p"images/tails.png")
i=random.randint(0,1)
if i == 1:
print("heads")
display(im)
else:
print("tails")
display(image)
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 = 10
blue = 0
red = 0
RedImg = Image.open(p"images/red.png")
BlueImg = Image.open(p"images/blue.png")
for i in range(n):
spin = random.randint(1,2)
if spin == 1: # head
blue = blue + 1
display(BlueImg)
else: # tail
red = red + 1
display(RedImg)
print('Number of blue:', blue)
print('Number of red:', red)
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 only shows how many birds died due to a natural disaster even though there is no corelation between natural disasters and the height (or other characteristics) of birds.
- 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)
Simulation Questions
- A and B- The wait time for rides depends on what type of ride it is if more people like a certain type of ride it means more people are going to wait in line for that ride meaning the wait time would be larger or smalled depending on the number of people in line. And if patrons don't like to walk far between rides the wait time will be large for rides which are closer together than those which are farther away
- A- This is non essential for the program to work since we don't care about grass when talking about foxes and rabbits
- A- Since this is a simulation we can't get the exact values form the simulation
- D- All of these are true since simulations take less time to run than observing real life, and there can be multiple variables and functions for different species and environments to be changed and mimiced
- B and D- Since control variables can be set easily it makes it easier to see the effect of specific factors and it would make the simulations detailed since it's easier to remove confounding variables
- C- Situations in real life ar extremely complex and it wouldn't be efficiant to account for all of these complexities so these situations must be simplified
import numpy as np
import matplotlib.pyplot as plt
G = 6.67e-11 ## gravitational constant
M1 = 1.989e30 ## sun mass
m2 = 5.97e24 ## earth mass
p0 = np.array([1.496e11, 0]) # initial position
v0 = np.array([0, 2.978e4]) # initial velocity
dt = 86400 ## used to get position once a day
t = 0
p = p0
v = v0
x_vals = [p[0]]
y_vals = [p[1]]
while t < 31536000: ##time (one year in the unit of seconds)
r = np.linalg.norm(p) ## resultant
F = -G*M1*m2*p/r**3 ## gravitational force equation
v = v + F/m2*dt ## velocity equation
p = p + v*dt ## position equation
x_vals.append(p[0])
y_vals.append(p[1])
t = t + dt ## goes onto the next time interval
## plotting the values
plt.plot(x_vals, y_vals)
plt.xlabel('x (m)')
plt.ylabel('y (m)')
plt.title('Planetary Motion of Earth')
plt.show()
How does your simulation help solve/mimic a real world problem?
This shows a simulation of how planets (specifically Earth) move around the sun over the course of a year and this makes it easier to predict where the planet will be on a given day. If used for other planets this can be used to help with launching rockets since it can tell where and when the rocket should be launched to ensure that it will land.
Is there any bias in your simulation? Meaning, are there any discrepancies between your program and the real event?
There may be some bias since this event has been simplified making it so that every possibility isn't accounted for.
Bonus
The psudocode below is used to simulate a dice roll to see the probability of getting a certain side in an x amount of dice rolls
diceRolls <-- INPUT()
value <-- INPUT()
REPEAT diceRolls TIMES {
roll ← RANDOM(1, 6)
IF (roll = value) {
countOfValue ← countOfValue + 1
}
}
probabilityOfSide <-- countOfValue/diceRolls
DISPLAY(probabilityOfSide)