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

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

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

  • “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.

import random

#Code, Code, Code

# Simulate rolling two dice
dice1 = random.randint(1, 6)  # Roll for the first die (random integer between 1 and 6)
dice2 = random.randint(1, 6)  # Roll for the second die (random integer between 1 and 6)

# Calculate the sum
total = dice1 + dice2

# Print the results
print(f"The first die rolled: {dice1}")
print(f"The second die rolled: {dice2}")
print(f"The total sum is: {total}")
The first die rolled: 5
The second die rolled: 1
The total sum is: 6

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

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

  • t = time (output)
  • h = height dropped from (input)
  • g = constant (given)
# Constant, Acceleration due to gravity (m/s^2)
def simulation(height_dropped):
    # Calculate time using the formula
    time_to_fall = math.sqrt((2 * height_dropped) / g)
    return time_to_fall

import math

# Constants
g = 9.81  # Acceleration due to gravity in m/s^2

# Get user input for height dropped
height_dropped = float(input("Enter the height dropped (in meters): "))

# Call the simulation function
time_to_fall = simulation(height_dropped)

# Print the result
print(f"The object will take approximately {time_to_fall:.2f} seconds to fall.")
The object will take approximately 3.67 seconds to fall.

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.

# Code Code Code
import random

def roll_dice():
    return random.randint(1, 6) + random.randint(1, 6)

def play_session():
    return roll_dice() >= 9

def simulate_gambling_sessions(num_sessions):
    sessions_won = 0
    for _ in range(num_sessions):
        if play_session():
            sessions_won += 1
    return sessions_won

num_sessions = 10000  
sessions_won = simulate_gambling_sessions(num_sessions)

jackpot_won = sessions_won >= 5

print(f"Out of {num_sessions} sessions, you won {sessions_won} sessions.")
if jackpot_won:
    print("Congratulations! You won the jackpot!")
else:
    print("Better luck next time.")
Out of 10000 sessions, you won 2853 sessions.
Congratulations! You won the jackpot!

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:
  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

# Initial parameters
altitude = 0
speed = 0
fuel = 100

print("Welcome to Flight Simulator!")

while altitude < 10000 and fuel > 0:
    altitude_change = random.randint(-200, 200)
    speed_change = random.randint(-10, 10)
    fuel_consumption = random.uniform(0.5, 1.5)

    altitude += altitude_change
    speed += speed_change
    fuel -= fuel_consumption

    altitude = max(altitude, 0)
    speed = max(speed, 0)  
    fuel = max(fuel, 0)

    print(f"Altitude: {altitude} feet | Speed: {speed} knots | Fuel: {fuel} gallons")

if altitude >= 10000:
    print("Congratulations! You have reached 10,000 feet.")
else:
    print("Oh no! You've run out of fuel. The flight was not successful.")

Welcome to Flight Simulator!
Altitude: 0 feet | Speed: 0 knots | Fuel: 98.85328275020068 gallons
Altitude: 30 feet | Speed: 1 knots | Fuel: 97.87757631808171 gallons
Altitude: 50 feet | Speed: 0 knots | Fuel: 96.65121119799089 gallons
Altitude: 4 feet | Speed: 4 knots | Fuel: 96.02992173544808 gallons
Altitude: 0 feet | Speed: 0 knots | Fuel: 94.68753828305199 gallons
Altitude: 106 feet | Speed: 0 knots | Fuel: 93.21063443515062 gallons
Altitude: 114 feet | Speed: 1 knots | Fuel: 92.30234199171666 gallons
Altitude: 296 feet | Speed: 7 knots | Fuel: 91.09928205670732 gallons
Altitude: 334 feet | Speed: 0 knots | Fuel: 90.39963609217456 gallons
Altitude: 534 feet | Speed: 9 knots | Fuel: 89.80858598920555 gallons
Altitude: 696 feet | Speed: 16 knots | Fuel: 89.0559573145506 gallons
Altitude: 787 feet | Speed: 7 knots | Fuel: 88.21214957572677 gallons
Altitude: 856 feet | Speed: 9 knots | Fuel: 87.30146292770594 gallons
Altitude: 775 feet | Speed: 0 knots | Fuel: 86.5159125280123 gallons
Altitude: 770 feet | Speed: 0 knots | Fuel: 85.89339863521673 gallons
Altitude: 834 feet | Speed: 0 knots | Fuel: 84.41978406206209 gallons
Altitude: 649 feet | Speed: 0 knots | Fuel: 83.5816875606464 gallons
Altitude: 469 feet | Speed: 0 knots | Fuel: 82.72516023001835 gallons
Altitude: 378 feet | Speed: 4 knots | Fuel: 81.92838497713866 gallons
Altitude: 178 feet | Speed: 0 knots | Fuel: 80.7060721272649 gallons
Altitude: 155 feet | Speed: 10 knots | Fuel: 79.51647013756342 gallons
Altitude: 17 feet | Speed: 10 knots | Fuel: 78.56183727886696 gallons
Altitude: 0 feet | Speed: 18 knots | Fuel: 77.95980640710663 gallons
Altitude: 9 feet | Speed: 19 knots | Fuel: 77.27361946081302 gallons
Altitude: 0 feet | Speed: 27 knots | Fuel: 76.63434505603226 gallons
Altitude: 0 feet | Speed: 18 knots | Fuel: 75.78280410500167 gallons
Altitude: 157 feet | Speed: 14 knots | Fuel: 75.19264308033316 gallons
Altitude: 357 feet | Speed: 5 knots | Fuel: 74.62850473319557 gallons
Altitude: 242 feet | Speed: 1 knots | Fuel: 73.3269159583344 gallons
Altitude: 423 feet | Speed: 4 knots | Fuel: 72.48277574261623 gallons
Altitude: 378 feet | Speed: 0 knots | Fuel: 71.16064600585172 gallons
Altitude: 265 feet | Speed: 0 knots | Fuel: 70.56737556192185 gallons
Altitude: 296 feet | Speed: 0 knots | Fuel: 69.93788384458902 gallons
Altitude: 165 feet | Speed: 8 knots | Fuel: 69.33685076022712 gallons
Altitude: 0 feet | Speed: 2 knots | Fuel: 68.19168632668689 gallons
Altitude: 0 feet | Speed: 0 knots | Fuel: 66.90117062167417 gallons
Altitude: 0 feet | Speed: 0 knots | Fuel: 65.95545161646457 gallons
Altitude: 0 feet | Speed: 8 knots | Fuel: 64.48132410864235 gallons
Altitude: 0 feet | Speed: 2 knots | Fuel: 63.90631756521353 gallons
Altitude: 6 feet | Speed: 5 knots | Fuel: 62.51190603339091 gallons
Altitude: 0 feet | Speed: 0 knots | Fuel: 61.578437405552066 gallons
Altitude: 27 feet | Speed: 0 knots | Fuel: 60.48680198584934 gallons
Altitude: 180 feet | Speed: 0 knots | Fuel: 59.39364571538403 gallons
Altitude: 29 feet | Speed: 0 knots | Fuel: 58.37025471518569 gallons
Altitude: 166 feet | Speed: 0 knots | Fuel: 57.36868303305093 gallons
Altitude: 132 feet | Speed: 0 knots | Fuel: 56.10583130948052 gallons
Altitude: 0 feet | Speed: 3 knots | Fuel: 55.47753888838829 gallons
Altitude: 0 feet | Speed: 0 knots | Fuel: 54.2011802965237 gallons
Altitude: 0 feet | Speed: 0 knots | Fuel: 53.62039584497496 gallons
Altitude: 7 feet | Speed: 0 knots | Fuel: 52.73678041925521 gallons
Altitude: 120 feet | Speed: 0 knots | Fuel: 51.844272443868675 gallons
Altitude: 116 feet | Speed: 7 knots | Fuel: 50.48981721616708 gallons
Altitude: 113 feet | Speed: 10 knots | Fuel: 49.68452275843518 gallons
Altitude: 249 feet | Speed: 8 knots | Fuel: 48.77719031840482 gallons
Altitude: 226 feet | Speed: 1 knots | Fuel: 47.6338828159658 gallons
Altitude: 58 feet | Speed: 7 knots | Fuel: 47.09913455282978 gallons
Altitude: 166 feet | Speed: 16 knots | Fuel: 46.00432038516698 gallons
Altitude: 311 feet | Speed: 18 knots | Fuel: 45.1108046907908 gallons
Altitude: 309 feet | Speed: 26 knots | Fuel: 43.791036746699305 gallons
Altitude: 393 feet | Speed: 21 knots | Fuel: 42.64825988567455 gallons
Altitude: 227 feet | Speed: 27 knots | Fuel: 41.59674700572637 gallons
Altitude: 425 feet | Speed: 30 knots | Fuel: 40.79652259929643 gallons
Altitude: 474 feet | Speed: 40 knots | Fuel: 39.33297261889358 gallons
Altitude: 449 feet | Speed: 38 knots | Fuel: 38.69649678397903 gallons
Altitude: 535 feet | Speed: 47 knots | Fuel: 38.0439815965306 gallons
Altitude: 424 feet | Speed: 55 knots | Fuel: 36.75006468789065 gallons
Altitude: 536 feet | Speed: 51 knots | Fuel: 35.73819936727327 gallons
Altitude: 527 feet | Speed: 47 knots | Fuel: 34.91186868645469 gallons
Altitude: 651 feet | Speed: 39 knots | Fuel: 34.38607356370389 gallons
Altitude: 679 feet | Speed: 35 knots | Fuel: 33.598227765880445 gallons
Altitude: 858 feet | Speed: 37 knots | Fuel: 33.04863206404531 gallons
Altitude: 957 feet | Speed: 41 knots | Fuel: 32.13308636064833 gallons
Altitude: 1057 feet | Speed: 46 knots | Fuel: 31.00832443749423 gallons
Altitude: 972 feet | Speed: 40 knots | Fuel: 30.21218513449295 gallons
Altitude: 1050 feet | Speed: 40 knots | Fuel: 28.92204852811848 gallons
Altitude: 961 feet | Speed: 37 knots | Fuel: 27.538834851308195 gallons
Altitude: 791 feet | Speed: 45 knots | Fuel: 26.637549981788865 gallons
Altitude: 654 feet | Speed: 35 knots | Fuel: 25.49304686193495 gallons
Altitude: 474 feet | Speed: 29 knots | Fuel: 24.29266190554094 gallons
Altitude: 509 feet | Speed: 22 knots | Fuel: 23.241172822430574 gallons
Altitude: 373 feet | Speed: 22 knots | Fuel: 21.945668518008752 gallons
Altitude: 449 feet | Speed: 18 knots | Fuel: 20.500696227302928 gallons
Altitude: 450 feet | Speed: 12 knots | Fuel: 19.912324181439256 gallons
Altitude: 461 feet | Speed: 4 knots | Fuel: 18.866490307943405 gallons
Altitude: 594 feet | Speed: 2 knots | Fuel: 18.083698072986127 gallons
Altitude: 757 feet | Speed: 0 knots | Fuel: 16.744030100722572 gallons
Altitude: 910 feet | Speed: 0 knots | Fuel: 16.16785256981265 gallons
Altitude: 1093 feet | Speed: 0 knots | Fuel: 15.46725206524294 gallons
Altitude: 1102 feet | Speed: 0 knots | Fuel: 14.902156753658726 gallons
Altitude: 1081 feet | Speed: 1 knots | Fuel: 13.719000830558699 gallons
Altitude: 1079 feet | Speed: 0 knots | Fuel: 12.549575179597328 gallons
Altitude: 1102 feet | Speed: 7 knots | Fuel: 11.593702706477686 gallons
Altitude: 908 feet | Speed: 5 knots | Fuel: 10.433928680319799 gallons
Altitude: 888 feet | Speed: 0 knots | Fuel: 9.73869218133605 gallons
Altitude: 910 feet | Speed: 5 knots | Fuel: 8.58377239577056 gallons
Altitude: 880 feet | Speed: 0 knots | Fuel: 7.718388868608937 gallons
Altitude: 834 feet | Speed: 0 knots | Fuel: 6.466906166686137 gallons
Altitude: 636 feet | Speed: 5 knots | Fuel: 5.936912669197984 gallons
Altitude: 549 feet | Speed: 0 knots | Fuel: 4.501461687349447 gallons
Altitude: 483 feet | Speed: 0 knots | Fuel: 3.058035796623554 gallons
Altitude: 494 feet | Speed: 9 knots | Fuel: 2.1732805057836173 gallons
Altitude: 666 feet | Speed: 18 knots | Fuel: 1.418181282250869 gallons
Altitude: 769 feet | Speed: 15 knots | Fuel: 0.49588162278984804 gallons
Altitude: 787 feet | Speed: 17 knots | Fuel: 0 gallons
Oh no! You've run out of fuel. The flight was not successful.

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

# Code Code Code
import random

def roll_dice():
    return random.randint(1, 12)

def play_session(money):
    dice_roll = roll_dice()

    if dice_roll <= 3:
        money -= 70
    elif 3 < dice_roll <= 6:
        money -= 40
    elif 6 < dice_roll < 9:
        money += 20
    elif dice_roll >= (9 + money):
        money += 50
    elif dice_roll == 12:
        money += 100

    return money

def simulate_gambling_sessions(num_sessions, starting_money):
    sessions_won = 0
    money = starting_money

    for _ in range(num_sessions):
        money = play_session(money)
        if money > 100:
            sessions_won += 1

    return sessions_won

starting_money = 100
num_sessions = 10000
sessions_won = simulate_gambling_sessions(num_sessions, starting_money)

jackpot_won = sessions_won >= 5

print(f"Out of {num_sessions} sessions, you won {sessions_won} sessions.")
if jackpot_won:
    print("Congratulations! You won the jackpot!")
else:
    print("Better luck next time.")
Out of 10000 sessions, you won 0 sessions.
Better luck next time.

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

#Code Code Code
while distance < 1000 and speed >= 5:
    if speed < max_speed:
        speed += acceleration
    else:
        speed = max_speed
    
    distance += speed
    time += 1

    if distance >= 1000 or speed <= 5:
        break

    speed -= deceleration

print(f"Final speed: {speed} m/s")
print(f"Distance covered: {distance} meters")
print(f"Time taken: {time} seconds")
Final speed: 0 m/s
Distance covered: 0 meters
Time taken: 0 seconds