Home

Simulations - Student Teach

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.

simulation

College Board Essential Knowledge

Simulation are absractions of more complex objects or phenomena for a specific purpose

Simulations utilize varying sets of values to reflect the changings states of a phenomenon

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.

simulations-vs-experiments

Rolling the Dice

craps-rolling-seven-7

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

#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.

import random

die1 = random.randint(1, 6)  
die2 = random.randint(1, 6)  

dice_sum = die1 + die2

print(f"die 1 = {die1}, die 2 = {die2}")
print(f"sum: {dice_sum}")
die 1 = 5, die 2 = 2
sum: 7

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

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.

gravity

# Constant, Acceleration due to gravity (m/s^2)
G = 9.81

import math

def simulation(height_dropped):
    time = math.sqrt((2 * height_dropped) / G)
    
    return time

height = float(input("Enter the height: "))

fall_time = simulation(height)
print(f"The time it takes for the object to fall from a height of {height} meters is {fall_time:.2f} seconds.")

The time it takes for the object to fall from a height of 10.0 meters is 1.43 seconds.

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
# Example For Loop

#Creating For Loop to repeat 4 times
for i in range(4):
    
    #Action that happens inside for loop
    print("This is run number: " + str(i))
    
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

total_sessions = 100000  
sessions_to_win_jackpot = 5
win_count = 0

for _ in range(total_sessions):
    dice1 = random.randint(1, 6)
    dice2 = random.randint(1, 6)
    total_roll = dice1 + dice2
    
    if total_roll >= 9:
        win_count += 1
        if win_count >= sessions_to_win_jackpot:
            break

odds_of_winning = win_count / total_sessions

print(f"out of {total_sessions} sessions yoou won {win_count} session.")
print(f"the odds of hitting the jackpot in {total_sessions} sessions are {odds_of_winning:.2%}.")

out of 100000 sessions yoou won 5 session.
the odds of hitting the jackpot in 100000 sessions are 0.01%.

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.

  1. Use random changes to simulate altitude, speed, and fuel changes.
  2. Keep the flight going until it reaches 10,000 feet or runs out of fuel.
  3. Make sure altitude, speed, and fuel remain realistic.
import random

altitude = 0
speed = 250  
fuel = 100

print("Welcome to Flight Simulator!")

altitude_change_limit = 500  
speed_change_limit = 10  
fuel_consumption_rate = 0.2  

while altitude < 10000 and fuel > 0:
    altitude_change = random.randint(-altitude_change_limit, altitude_change_limit)
    speed_change = random.uniform(-speed_change_limit, speed_change_limit)
    fuel_consumption = speed * fuel_consumption_rate
    
    altitude = max(0, altitude + altitude_change)  
    speed = max(0, speed + speed_change)  
    fuel = max(0, fuel - fuel_consumption)
    
    print(f"Altitude: {altitude} feet | Speed: {speed} knots | Fuel: {fuel:.2f}%")
    
if altitude >= 10000:
    print("Congratulations! You've reached 10,000 feet and completed the flight.")
else:
    print("Out of fuel. The flight has ended.")

Welcome to Flight Simulator!
Altitude: 0 feet | Speed: 241.74691363435053 knots | Fuel: 50.00%
Altitude: 0 feet | Speed: 251.59819599186451 knots | Fuel: 1.65%
Altitude: 396 feet | Speed: 248.13716301197758 knots | Fuel: 0.00%
Out of fuel. The flight has ended.

QUIZ TIME


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

starting_money = 100
sessions_won = 0
total_winnings = 0
rounds_played = 0

jackpot_threshold = 5

while sessions_won < jackpot_threshold and starting_money > 0:
    dice1 = random.randint(1, 6)
    dice2 = random.randint(1, 6)
    dice_roll = dice1 + dice2
    
    if dice_roll <= 3:
        starting_money -= 70
    elif dice_roll > 3 and dice_roll <= 6:
        starting_money -= 40
    elif dice_roll > 6 and dice_roll < 9:
        starting_money += 20
    elif dice_roll >= 9:
        starting_money += 50
        sessions_won += 1
    
    rounds_played += 1

    if sessions_won >= jackpot_threshold:
        total_winnings = starting_money + 100  
        
    if starting_money <= 0:
        print(f"You ran out of money after {rounds_played} rounds.")
        break

print(f"Number of sessions won: {sessions_won}")
print(f"Total winnings: ${total_winnings}")
print(f"Rounds played: {rounds_played}")

Number of sessions won: 5
Total winnings: $160
Rounds played: 22

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_speed = 10
acceleration_rate = 2
deceleration_rate = -1
max_speed = 20
initial_distance = 0
target_distance = 1000
min_speed = 5

speed = initial_speed
distance = initial_distance
time = 0

while distance < target_distance and speed >= min_speed:
    time_to_max_speed = (max_speed - speed) / acceleration_rate
    distance_covered_acceleration = speed * time_to_max_speed + 0.5 * acceleration_rate * time_to_max_speed ** 2

    if distance + distance_covered_acceleration >= target_distance:
        time += (-speed + (speed ** 2 + 2 * acceleration_rate * (target_distance - distance)) ** 0.5) / acceleration_rate
        speed = max_speed
        distance = target_distance
    else:
        time += time_to_max_speed
        speed = max_speed
        distance += distance_covered_acceleration

        if distance < target_distance:
            time_to_decelerate = (speed - min_speed) / abs(deceleration_rate)
            distance_covered_deceleration = speed * time_to_decelerate + 0.5 * deceleration_rate * time_to_decelerate ** 2

            if distance + distance_covered_deceleration >= target_distance:
                time += (-speed + (speed ** 2 - 2 * deceleration_rate * (distance - target_distance)) ** 0.5) / abs(deceleration_rate)
                speed = min_speed
                distance = target_distance
            else:
                time += time_to_decelerate
                speed = min_speed
                distance += distance_covered_deceleration

print(f"Final Speed: {speed} m/s")
print(f"Distance Covered: {distance} meters")
print(f"Time Taken: {time} seconds")

Final Speed: 5 m/s
Distance Covered: 1000 meters
Time Taken: 67.91103500742244 seconds
© 2024    •  Powered by Soopr   •  Theme  Moonwalk