Simulations
A simulation is the use of a computer software to represent the dynamic responses of one system by the behaviour of another system modeled after it. A simulation uses a mathematical descriptions, or models, of a real system in the form of a computer program.
College Board Essential Knowledge
Simulation are absractions of more complex objects or phenomena for a specific purpose
- Mimic Real World Events
- Allows investigation of phenomenons without contraints of the Real World
- Helps you draw accurate inferences
Simulations utilize varying sets of values to reflect the changings states of a phenomenon
- simulations can simplfly things for functionality
- Simulations can contain bias from real world elements, that were chosen to be included or excluded
Simulations work best when the real world experemnts are too impractical or time consuming. For example, simulating how different cars behave when they crash, would be much better than crashng actual cars in the real world, which would be expensive and dangerous.
Rolling the Dice
Simulating something like a dice roll in real life would require accounting for things like: weight, flaws in design, thrust, and gravity.
- KEEP IT SIMPLE! just use a random-number generator! Ignore minor causes of variablility
Random
- “Random” is a built-in python function that allow the user to draw a random value from a set range.
- A Random Number Generator (RNG) is a common simulation that selects a random value from an array.
- The following code cell utilizes “random” to select a number from 1 to 100.
#imports random module so we can use it in our code
import random
#sets variable random_number as a random number between 1 and 100
random_number = random.randint(1, 100)
#Printing out your random Number
print(random_number)
More complex usage of “random”; Coin Toss Simulation
import random
def flip_coin():
return random.choice(["Heads", "Tails"])
def coin_flip_simulation(num_flips):
heads_count = 0
tails_count = 0
for _ in range(num_flips):
result = flip_coin()
if result == "Heads":
heads_count += 1
else:
tails_count += 1
return heads_count, tails_count
if __name__ == "__main__":
num_flips = 1000 #This is the number of coin flips you want to simulate
heads, tails = coin_flip_simulation(num_flips)
print("Number of Heads: "+ str(heads))
print("Number of Tails: " + str(tails))
print("Heads Probability: "+ str({heads / num_flips}))
print("Tails Probability: "+ str({tails / num_flips}))
Popcorn Hack #1
Utilize “random” to create a basic simulation of a rolling TWO dice. Print the sum of both dice rolls. Remember to practice good syntax when naming your variables.
# Execute a simulation of rolling two six-sided dice
first_die_roll = random.randint(1, 6) # Generate a random number for the first die
second_die_roll = random.randint(1, 6) # Generate a random number for the second die
# Add the values of the two dice to get the total
sum_of_dice = first_die_roll + second_die_roll
# Display the outcomes of the rolls
print(f"Roll of die one: {first_die_roll}")
print(f"Roll of die two: {second_die_roll}")
print(f"Combined total: {sum_of_dice}")
Roll of die one: 3
Roll of die two: 6
Combined total: 9
Algorithms
Simulations often utilize algorithms and equations to perform tasks because simulations don’t always have the same output
- the output of a simulation depends on the input
An algorithm is a finite sequence of instructions used to solve problems or perform computations.
- commonly used alongside functions
Example Algorithm in a function
#Defining Function
def algorithm(input):
#Manipulating input and preparing it for the output.
output = input+2
#Return the output
return output
#Call the Function to start the algorithm
algorithm(5)
7
Mathematics
- Math can also prove to be very useful in certain types of situations.
- Commonly used along with Algorithms when simulating various things
Popcorn Hack #2
Simulate how long an object will fall for using an algorithm, with user-inputed variables for height dropped. Use the following formula as a reference.
- t = time (output)
- h = height dropped from (input)
- g = constant (given)
# Define the gravitational constant in meters per second squared
gravitational_constant = 9.81 # This value, 'gravitational_constant', should be used throughout
# Prompt the user to input the fall height in meters
fall_height_meters = float(input("Please input the height (in meters) from which the object will fall: "))
# Compute the fall time using the square root of twice the height divided by gravity
time_to_fall = (2 * fall_height_meters / gravitational_constant) ** 0.5
# Output the calculated time to the user
print(f"It will take about {time_to_fall:.2f} seconds for the object to hit the ground.")
It will take about 0.78 seconds for the object to hit the ground.
Using Loops in Simulations
For loops can also be used in simulations
- They can simulate events that repeat but don’t always have the same output
# Demonstration of a For Loop
# Set up a For Loop to execute four times
for iteration in range(4):
# Perform this action each time through the loop
print("Iteration count is currently: " + str(iteration))
This is run number: 0
This is run number: 1
This is run number: 2
This is run number: 3
Popcorn Hack #3
You are gambling addict (sigma).
Each session you roll 2 dice.
If your dice roll is greater than or equal to 9 you win the session.
If you win over 5 sessions, you win the jackpot.
Simulate your odds to predict if you will hit the jackpot (how many rounds did you win?) using a for loop and random.
import random
# Set simulation parameters
num_simulations = 10000 # Total number of game sessions to be simulated
winning_session_count = 5 # Required number of winning sessions to hit the jackpot
# Initialize counters for tracking the number of wins and jackpot victories
wins_count = 0
jackpot_count = 0
# Conduct the session simulations
for _ in range(num_simulations):
# Generate random outcomes for two dice
die_one = random.randint(1, 6)
die_two = random.randint(1, 6)
# Sum the outcomes of the dice rolls
total_dice = die_one + die_two
# Increment win counter if the session is won
if total_dice >= 9:
wins_count += 1
# Increment jackpot counter if the threshold for jackpot wins is reached
if wins_count >= winning_session_count:
jackpot_count += 1
# Output the simulation results
print(f"Ran {num_simulations} gaming sessions.")
print(f"Wins achieved in separate sessions: {wins_count}")
print(f"Number of times the jackpot was won (at least 5 session wins): {jackpot_count}")
BONUS POPCORN HACK
Welcome to Flight Simulator! Your goal is to complete a Python program that simulates a flight We’ve set up some initial values for altitude, speed, and fuel. Your task is to update these values to make the flight more realistic.
- Your mission:
- Use random changes to simulate altitude, speed, and fuel changes.
- Keep the flight going until it reaches 10,000 feet or runs out of fuel.
- Make sure altitude, speed, and fuel remain realistic.
current_altitude = 0
current_speed = 250
remaining_fuel = 100
print("Welcome to the Aero Dynamics Simulator!")
max_altitude_variation = 500
max_speed_variation = 10
rate_of_fuel_use = 0.2
# Flight simulation loop
while current_altitude < 10000 and remaining_fuel > 0:
change_in_altitude = random.randint(-max_altitude_variation, max_altitude_variation)
change_in_speed = random.uniform(-max_speed_variation, max_speed_variation)
fuel_used = current_speed * rate_of_fuel_use
current_altitude = max(0, current_altitude + change_in_altitude)
current_speed = max(0, current_speed + change_in_speed)
remaining_fuel = max(0, remaining_fuel - fuel_used)
print(f"Current altitude: {current_altitude} feet | Current speed: {current_speed} knots | Remaining fuel: {remaining_fuel:.2f}%")
# Post-flight status
if current_altitude >= 10000:
print("You have successfully ascended beyond 10,000 feet. The simulation is a success.")
else:
print("The aircraft has run out of fuel and the simulation is now concluded.")
QUIZ TIME
- Quick true or false quiz, whoever answers this correctly(raise your hand) gets a piece of gum or a dinero.
T or F
- A simulation will always have the same result. T or F
- A simulation investigates a phenomenom without real-world constraints of time, money, or safety. T or F
- A simulation has results which are more accurate than an experiment, T or F
- A simulation can model real-worl events that are not practical for experiments
HOMEWORK HACK #1
First finish Popcorn Hack #3. Expand the simulation to involve your own money.
starting money: $100
(Dice Roll <= 3) → lose $70
( 6> Dice Roll >3) → lose $40
( 9> Dice Roll >=6) → win $20
( Dice Roll>= 9 + Session Win) → win $50
Jackpot → win $100
import random
initial_funds = 100
victorious_sessions = 0
accumulated_earnings = 0
rounds_completed = 0
required_wins_for_jackpot = 5
# Run the gambling simulation
while victorious_sessions < required_wins_for_jackpot and initial_funds > 0:
first_die = random.randint(1, 6)
second_die = random.randint(1, 6)
sum_of_dice = first_die + second_die
# Apply the game rules for winning or losing money
if sum_of_dice <= 3:
initial_funds -= 70
elif 4 <= sum_of_dice <= 6:
initial_funds -= 40
elif 7 <= sum_of_dice < 9:
initial_funds += 20
else: # This covers the case where sum_of_dice >= 9
initial_funds += 50
victorious_sessions += 1
rounds_completed += 1
# Check for jackpot win condition
if victorious_sessions >= required_wins_for_jackpot:
accumulated_earnings = initial_funds + 100 # Jackpot bonus
# If funds are depleted, end the game
if initial_funds <= 0:
print(f"Your funds have been depleted after {rounds_completed} rounds.")
break
# Display the results
print(f"Sessions won: {victorious_sessions}")
print(f"Total earnings: ${accumulated_earnings}")
print(f"Total rounds: {rounds_completed}")
HOMEWORK HACK #2
Given initial parameters for a car simulation, including its initial speed, acceleration rate, deceleration rate, maximum speed, and initial distance, write a program to simulate the car’s journey and determine the final speed, distance covered, and time taken before it either covers 1000 meters or slows down to below 5 m/s?
# Initial parameters
speed = 0 # Initial speed
acceleration = 2 # Acceleration rate in m/s^2
deceleration = 1 # Deceleration rate in m/s^2
max_speed = 60 # Maximum speed in m/s
distance = 0 # Initial distance
time = 0 # Initial time
# Parameters
desired_distance = 1000 # Distance goal in meters
threshold_speed = 5 # Threshold speed in meters per second
# Commence the vehicle's movement
while distance < desired_distance and speed >= threshold_speed:
# Determine the distance traversed in this interval
travelled_distance = speed + 0.5 * acceleration * (time_interval ** 2)
# Ascertain whether the vehicle has attained its top speed
if speed < peak_speed:
speed += acceleration * time_interval
else:
speed = peak_speed
# Refresh the total distance and the elapsed time
distance += travelled_distance
elapsed_time += time_interval
# Output the outcome
if distance >= desired_distance:
print(f"Distance travelled by the car: {distance:.2f} meters.")
print(f"Reached speed: {speed:.2f} m/s")
print(f"Duration: {elapsed_time} seconds")
else:
print("The car decelerated to under 5 m/s before achieving the 1000-meter mark.")