Unit 3 Lesson 16, Student Copy
- Hack #1 - Class Notes
- Hack #2 - Functions Classwork
- Hack #3 - Binary Simulation Problem
- Hack #4 - Thinking through a problem
- Hack 5 - Applying your knowledge to situation based problems
- Hack #6 / Challenge - Taking real life problems and implementing them into code
Hack #1 - Class Notes
In this section, I take my own notes on the section. I have split it up into a vocabulary section and a section for miscellaneous class notes.
Vocabulary Simulations: abstractions that mimic more complex objects or phenomena from the real world. (The purpose is drawing inferences without the contraints of the real world.)
Variance: random chance, simulated through random number generation in simulations.
Miscellaneous Class Notes Typically, simulations leave out specific details or simplify complex aspects. It is crucial, however, to have variables to represent variance in the situation. Simulations often contain some amount of bias. Variability and randomness exists inherently in the world, and we can represent this with random number generation.
Here are some helpful functions for these simulations:
import random
min = int(input("WHat is lowest num"))
max = int(input("HIghest num please"))
x = random.randint(min,max)
print(x)
I entered the numbers 4 and 8 and it found the number in between which is 6.
Why is this simulation considered an abstraction?
It uses a conditional to execute one part of the code only when a particular condition is met. It uses a REPEAT loop to run the same block of code multiple times. It simplifies a real-world scenario into something that can be modeled in code and executed on a computer. It does not request input from the user or display output to the user. Explanation: The simulation is considered an abstraction because it is represented in separate terms (abstracted) into a computer language, but still made to function in its intended circumstances.
import random
x = random.randint(1, 100)
print(x)
Random coin flip
import random
def coinflip(): #def function
randomflip = random.randint(0, 2) #picks either 0 or 1 randomly (50/50 chance of either)
if randomflip == 0 and 1: #assigning 0 to be heads--> if 0 is chosen then it will print, "Heads"
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()
import random
print("Please pick the lower bound of the RNG.")
x = int(input())
print("You picked", str(x) + ".")
print("Please pick the upper bound of the RNG.")
y = int(input())
print("You picked", str(y) + ".")
print("Your random number is...", str(random.randint(x, y)) + ".")
Heres something that requires user input.
import random
def generate_random_int(): # function for generating random int
return random.randint(0, 255)
def convert_to_binary(decimal): # function for converting decimal to binary
i = 7
binary = ""
while i >= 0:
if decimal % (2**i) == decimal:
binary += "0"
i -= 1
else:
binary += "1"
decimal -= 2**i
i -= 1
return binary
def determine_survivor_status(binary): # function to assign position
survivors = ["Drew", "Bob", "Mark", "Ashely" , "Twig", "Elfen Child", "Jeffrey", "Kid in Basement"]
i = 0
while i < len(survivors):
if binary[i] == "1":
temp = "Zombie"
else:
temp = "Human"
survivors[i] = (survivors[i], temp)
i += 1
for name, status in survivors:
print(name + ":", status)
determine_survivor_status(convert_to_binary(generate_random_int()))
I changed the function name to roll_dice and the parameter to num_rolls. I also used a for loop to iterate over the number of rolls instead of a while loop. Additionally, I changed the print statement to print "Dice rolls: " and added a space after each roll when printing the rolls.
import random
def roll_dice(num_rolls):
dice_rolls = []
for i in range(num_rolls):
dice_rolls.append(random.randint(1, 6))
return dice_rolls
rolls = roll_dice(5)
print("Dice rolls: ", end='')
for roll in rolls:
print(roll, end=' ')
- A researcher gathers data about the effect of Advanced Placement®︎ classes on students' success in college and career, and develops a simulation to show how a sequence of AP classes affect a hypothetical student's pathway.Several school administrators are concerned that the simulation contains bias favoring high-income students, however.
- answer options:
- The simulation is an abstraction and therefore cannot contain any bias
- The simulation may accidentally contain bias due to the exclusion of details.
- If the simulation is found to contain bias, then it is not possible to remove the bias from the simulation.
- The only way for the simulation to be biased is if the researcher intentionally used data that favored their desired output.
- answer options:
- Jack is trying to plan his financial future using an online tool. The tool starts off by asking him to input details about his current finances and career. It then lets him choose different future scenarios, such as having children. For each scenario chosen, the tool does some calculations and outputs his projected savings at the ages of 35, 45, and 55.Would that be considered a simulation and why?
- answer options
- No, it's not a simulation because it does not include a visualization of the results.
- No, it's not a simulation because it does not include all the details of his life history and the future financial environment.
- Yes, it's a simulation because it runs on a computer and includes both user input and computed output.
- Yes, it's a simulation because it is an abstraction of a real world scenario that enables the drawing of inferences.
- answer options
- Sylvia is an industrial engineer working for a sporting goods company. She is developing a baseball bat that can hit balls with higher accuracy and asks their software engineering team to develop a simulation to verify the design.Which of the following details is most important to include in this simulation?
- answer options
- Realistic sound effects based on the material of the baseball bat and the velocity of the hit
- A depiction of an audience in the stands with lifelike behavior in response to hit accuracy
- Accurate accounting for the effects of wind conditions on the movement of the ball
- A baseball field that is textured to differentiate between the grass and the dirt
- answer options
- Ashlynn is an industrial engineer who is trying to design a safer parachute. She creates a computer simulation of the parachute opening at different heights and in different environmental conditions.What are advantages of running the simulation versus an actual experiment?
- answer options
- The simulation will not contain any bias that favors one body type over another, while an experiment will be biased.
- The simulation can be run more safely than an actual experiment
- The simulation will accurately predict the parachute's safety level, while an experiment may be inaccurate due to faulty experimental design.
- The simulation can test the parachute design in a wide range of environmental conditions that may be difficult to reliably reproduce in an experiment.
- this question has 2 correct answers
- answer options
- YOUR OWN QUESTION; can be situational, pseudo code based, or vocab/concept based
- YOUR OWN QUESTION; can be situational, pseudo code based, or vocab/concept based
import random
# New list of questions
questions = [
{
"q": "1. How does a simulation differ from an experiment?",
"a": "a. A simulation is a theoretical representation of a real-world process, while an experiment is a practical test of a hypothesis.\nb. A simulation is a practical test of a hypothesis, while an experiment is a theoretical representation of a real-world process.\nc. A simulation and an experiment are the same thing.\nd. A simulation is a representation of a real-world process that is more accurate than an experiment.",
"correct": "a"
},
{
"q": "2. How is random variability accounted for in simulations?",
"a": "a. By using clear frontend visualizations of the scenario.\nb. By connecting to an extensive API with historical data.\nc. By using random or pseudo-random number generation.\nd. By using inconsistent interpretation of concrete conditions.",
"correct": "c"
},
{
"q": "3. Which of the following is an example of a simulation?",
"a": "a. A computer program that predicts the weather based on data from weather stations.\nb. A scale model of a city used to test traffic flow.\nc. A physical model of an airplane used to test its flight capabilities.\nd. All of the above are examples of simulations.",
"correct": "d"
},
{
"q": "4. What are some potential limitations of simulations?",
"a": "a. They may not be able to account for all variables and complexities of the real world.\nb. They may be biased due to the assumptions and data used in the simulation.\nc. They are always less accurate than real-world experiments.\nd. All of the above are potential limitations of simulations.",
"correct": "d"
},
{
"q": "5. How can simulations be used in decision-making?",
"a": "a. By providing a realistic representation of potential outcomes.\nb. By allowing for the testing of different scenarios and scenarios that may not be practical or ethical to test in the real world.\nc. By providing a way to draw inferences about real-world processes.\nd. All of the above are ways in which simulations can be used in decision-making.",
"correct": "d"
}
]
validresponse = ["a", "b", "c", "d"]
score = 0
# Randomize the order of the questions
random.shuffle(questions)
# Iterate through each question and ask for input
for question in questions:
print(question["q"])
print(question["a"])
user_response = input("Enter the letter of your answer: ")
if user_response.lower() == question["correct"]:
score += 1
print("Correct! Your score is now {}.".format(score))
elif user_response.lower() not in validresponse:
print("Invalid input. Please enter a letter from 'a' to 'd'.")
else:
print("Incorrect. The correct answer is {}. Your score is now {}.".format(question["correct"], score))
# Print final score
print("Your final")
The quiz iterates through each question in the list and presents it to the user. The user is asked to enter the letter of their answer, and their response is checked against the correct answer for that question. If the user's answer is correct, their score is incremented by 1. If their answer is incorrect, their score remains the same. If the user's input is not one of the valid response letters ('a', 'b', 'c', or 'd'), a message is displayed to the user indicating that their input was invalid.
Create your own simulation based on your experiences/knowledge! Be creative! Think about instances in your own life, science, puzzles that can be made into simulations
Some ideas to get your brain running: A simulation that breeds two plants and tells you phenotypes of offspring, an adventure simulation...
import random
days_of_week = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
for day in days_of_week:
wake_up_time = f"7:{random.randint(0, 3)}{random.randint(0, 9)}am"
print(f"Woke up {day} at {wake_up_time}")