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)
33

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}))
Number of Heads: 501
Number of Tails: 499
Heads Probability: {0.501}
Tails Probability: {0.499}

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

def roll_die():
    return random.randint(1, 6)  # Simulate a single die roll (1 to 6)

def dice_roll_simulation(num_rolls):
    sum_of_rolls = 0
    for _ in range(num_rolls):
        roll1 = roll_die()
        roll2 = roll_die()
        sum_of_rolls += roll1 + roll2
    return sum_of_rolls

if __name__ == "__main__":
    num_rolls = 1000  # Number of dice rolls you want to simulate
    total_sum = dice_roll_simulation(num_rolls)
    average_sum = total_sum / num_rolls
    
    print("Average Sum of Two Dice Rolls: {:.2f}".format(average_sum))

Average Sum of Two Dice Rolls: 7.04

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)
G = 9.81 

height_dropped = float(input("enter your number"))
def simulation(height_dropped):
    # Code Code Code
    import math
    
    time_to_fall = math.sqrt((2 * height_dropped) / G)
    return time_to_fall
    
    time_to_fall - simulation(height_dropped)
    
    print(object will take (time_to_fall: .2f) seconds to fall)
  Cell In[30], line 14
    print(object will take (time_to_fall: .2f) seconds to fall)
                                           ^
SyntaxError: invalid decimal literal

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

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

# Simulate the game
total_rounds = 0
rounds_won = 0

while rounds_won < 5:  # Continue until you win the jackpot (5 sessions won)
    total_rounds += 1
    wins_in_session = 0
    
    for _ in range(2):  # Simulate rolling the dice in 2 sessions per round
        dice_roll = roll_two_dice()
        
        if dice_roll >= 9:
            wins_in_session += 1
    
    if wins_in_session >= 1:  # You win a session if you get at least one win
        rounds_won += 1

jackpot_probability = rounds_won / total_rounds  # Calculate the probability

print(f"Simulated {total_rounds} rounds.")
print(f"Jackpot won after {rounds_won} sessions.")
print(f"Estimated Jackpot Probability: {jackpot_probability:.2%}")

Simulated 12 rounds.
Jackpot won after 5 sessions.
Estimated Jackpot Probability: 41.67%

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!")

# Simulation loop
while altitude < 10000 and fuel > 0:
    # Simulate altitude change
    altitude_change = random.randint(100, 500)
    altitude += altitude_change

    # Ensure altitude stays within realistic bounds (0 to 10000 feet)
    altitude = max(0, min(altitude, 10000))

    # Simulate speed change
    speed_change = random.randint(10, 50)
    speed += speed_change

    # Ensure speed stays within realistic bounds (100 to 600 knots)
    speed = max(100, min(speed, 600))

    # Simulate fuel consumption
    fuel_consumption = random.uniform(0.1, 2.0)
    fuel -= fuel_consumption

    # Ensure fuel remains non-negative
    fuel = max(0, fuel)

    # Display current status
    print(f"Altitude: {altitude} feet, Speed: {speed} knots, Fuel: {fuel:.2f} gallons")

# End of simulation
if altitude >= 10000:
    print("Reached 10,000 feet. Mission accomplished!")
else:
    print("Out of fuel. Mission failed!")

Welcome to Flight Simulator!
Altitude: 242 feet, Speed: 100 knots, Fuel: 99.52 gallons
Altitude: 508 feet, Speed: 141 knots, Fuel: 98.05 gallons
Altitude: 638 feet, Speed: 155 knots, Fuel: 97.76 gallons
Altitude: 1022 feet, Speed: 187 knots, Fuel: 97.54 gallons
Altitude: 1269 feet, Speed: 206 knots, Fuel: 96.36 gallons
Altitude: 1615 feet, Speed: 254 knots, Fuel: 95.32 gallons
Altitude: 1900 feet, Speed: 304 knots, Fuel: 94.15 gallons
Altitude: 2090 feet, Speed: 321 knots, Fuel: 92.31 gallons
Altitude: 2323 feet, Speed: 362 knots, Fuel: 91.00 gallons
Altitude: 2489 feet, Speed: 400 knots, Fuel: 90.86 gallons
Altitude: 2783 feet, Speed: 419 knots, Fuel: 89.95 gallons
Altitude: 2890 feet, Speed: 452 knots, Fuel: 88.03 gallons
Altitude: 3162 feet, Speed: 483 knots, Fuel: 87.34 gallons
Altitude: 3565 feet, Speed: 502 knots, Fuel: 85.54 gallons
Altitude: 3752 feet, Speed: 522 knots, Fuel: 84.06 gallons
Altitude: 4034 feet, Speed: 535 knots, Fuel: 83.38 gallons
Altitude: 4390 feet, Speed: 548 knots, Fuel: 82.37 gallons
Altitude: 4643 feet, Speed: 591 knots, Fuel: 81.52 gallons
Altitude: 4857 feet, Speed: 600 knots, Fuel: 81.32 gallons
Altitude: 5221 feet, Speed: 600 knots, Fuel: 80.52 gallons
Altitude: 5582 feet, Speed: 600 knots, Fuel: 80.22 gallons
Altitude: 5979 feet, Speed: 600 knots, Fuel: 79.62 gallons
Altitude: 6323 feet, Speed: 600 knots, Fuel: 78.22 gallons
Altitude: 6491 feet, Speed: 600 knots, Fuel: 77.73 gallons
Altitude: 6700 feet, Speed: 600 knots, Fuel: 75.79 gallons
Altitude: 7147 feet, Speed: 600 knots, Fuel: 75.53 gallons
Altitude: 7549 feet, Speed: 600 knots, Fuel: 74.97 gallons
Altitude: 7785 feet, Speed: 600 knots, Fuel: 73.90 gallons
Altitude: 7910 feet, Speed: 600 knots, Fuel: 72.45 gallons
Altitude: 8260 feet, Speed: 600 knots, Fuel: 71.29 gallons
Altitude: 8520 feet, Speed: 600 knots, Fuel: 71.08 gallons
Altitude: 8742 feet, Speed: 600 knots, Fuel: 69.57 gallons
Altitude: 9205 feet, Speed: 600 knots, Fuel: 69.28 gallons
Altitude: 9323 feet, Speed: 600 knots, Fuel: 69.14 gallons
Altitude: 9642 feet, Speed: 600 knots, Fuel: 67.86 gallons
Altitude: 10000 feet, Speed: 600 knots, Fuel: 67.45 gallons
Reached 10,000 feet. Mission accomplished!

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 parameters
altitude = 0
speed = 0
fuel = 100
money = 100  # Starting money

print("Welcome to Flight Simulator!")

# Simulation loop
while altitude < 10000 and fuel > 0:
    # Simulate altitude change
    altitude_change = random.randint(100, 500)
    altitude += altitude_change

    # Ensure altitude stays within realistic bounds (0 to 10000 feet)
    altitude = max(0, min(altitude, 10000))

    # Simulate speed change
    speed_change = random.randint(10, 50)
    speed += speed_change

    # Ensure speed stays within realistic bounds (100 to 600 knots)
    speed = max(100, min(speed, 600))

    # Simulate fuel consumption
    fuel_consumption = random.uniform(0.1, 2.0)
    fuel -= fuel_consumption

    # Ensure fuel remains non-negative
    fuel = max(0, fuel)

    # Simulate dice roll
    dice_roll = random.randint(1, 12)

    # Update money based on dice roll
    if dice_roll <= 3:
        money -= 70
    elif 6 > dice_roll > 3:
        money -= 40
    elif 9 > dice_roll >= 6:
        money += 20
    elif dice_roll >= 9:
        money += 50

    # Display current status including money
    print(f"Altitude: {altitude} feet, Speed: {speed} knots, Fuel: {fuel:.2f} gallons, Money: ${money:.2f}")

# End of simulation
if altitude >= 10000:
    print("Reached 10,000 feet. Mission accomplished!")
else:
    print("Out of fuel. Mission failed!")

# Check for Jackpot and update money
if dice_roll == 12:
    money += 100
    print("Congratulations! You've won the Jackpot! $100 added to your money.")

Welcome to Flight Simulator!
Altitude: 368 feet, Speed: 100 knots, Fuel: 99.42 gallons, Money: $150.00
Altitude: 659 feet, Speed: 143 knots, Fuel: 97.78 gallons, Money: $110.00
Altitude: 1087 feet, Speed: 155 knots, Fuel: 96.99 gallons, Money: $160.00
Altitude: 1436 feet, Speed: 187 knots, Fuel: 96.67 gallons, Money: $180.00
Altitude: 1914 feet, Speed: 215 knots, Fuel: 94.79 gallons, Money: $200.00
Altitude: 2377 feet, Speed: 236 knots, Fuel: 94.62 gallons, Money: $160.00
Altitude: 2696 feet, Speed: 250 knots, Fuel: 93.39 gallons, Money: $90.00
Altitude: 2996 feet, Speed: 273 knots, Fuel: 91.50 gallons, Money: $110.00
Altitude: 3409 feet, Speed: 308 knots, Fuel: 90.37 gallons, Money: $40.00
Altitude: 3688 feet, Speed: 320 knots, Fuel: 89.56 gallons, Money: $60.00
Altitude: 3957 feet, Speed: 360 knots, Fuel: 88.70 gallons, Money: $110.00
Altitude: 4158 feet, Speed: 400 knots, Fuel: 87.84 gallons, Money: $160.00
Altitude: 4368 feet, Speed: 419 knots, Fuel: 86.86 gallons, Money: $210.00
Altitude: 4796 feet, Speed: 429 knots, Fuel: 86.20 gallons, Money: $140.00
Altitude: 5122 feet, Speed: 461 knots, Fuel: 84.67 gallons, Money: $160.00
Altitude: 5346 feet, Speed: 508 knots, Fuel: 84.07 gallons, Money: $180.00
Altitude: 5741 feet, Speed: 544 knots, Fuel: 82.76 gallons, Money: $110.00
Altitude: 5954 feet, Speed: 594 knots, Fuel: 80.76 gallons, Money: $130.00
Altitude: 6194 feet, Speed: 600 knots, Fuel: 79.68 gallons, Money: $180.00
Altitude: 6606 feet, Speed: 600 knots, Fuel: 77.68 gallons, Money: $110.00
Altitude: 6751 feet, Speed: 600 knots, Fuel: 77.15 gallons, Money: $40.00
Altitude: 7019 feet, Speed: 600 knots, Fuel: 76.94 gallons, Money: $60.00
Altitude: 7472 feet, Speed: 600 knots, Fuel: 76.05 gallons, Money: $80.00
Altitude: 7834 feet, Speed: 600 knots, Fuel: 74.13 gallons, Money: $10.00
Altitude: 7974 feet, Speed: 600 knots, Fuel: 72.50 gallons, Money: $60.00
Altitude: 8358 feet, Speed: 600 knots, Fuel: 71.39 gallons, Money: $80.00
Altitude: 8546 feet, Speed: 600 knots, Fuel: 70.25 gallons, Money: $40.00
Altitude: 8892 feet, Speed: 600 knots, Fuel: 69.62 gallons, Money: $-30.00
Altitude: 9096 feet, Speed: 600 knots, Fuel: 67.62 gallons, Money: $20.00
Altitude: 9311 feet, Speed: 600 knots, Fuel: 66.80 gallons, Money: $40.00
Altitude: 9534 feet, Speed: 600 knots, Fuel: 66.60 gallons, Money: $0.00
Altitude: 9806 feet, Speed: 600 knots, Fuel: 64.73 gallons, Money: $-40.00
Altitude: 10000 feet, Speed: 600 knots, Fuel: 63.07 gallons, Money: $-80.00
Reached 10,000 feet. Mission accomplished!

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?

import random

# Initial parameters
initial_speed = 50  # Initial speed in m/s
max_acceleration_rate = 4  # Maximum acceleration rate in m/s^2
max_deceleration_rate = 3  # Maximum deceleration rate in m/s^2
max_speed = 80  # Maximum speed in m/s
initial_distance = 0  # Initial distance in meters

# Initialize variables
speed = initial_speed
distance = initial_distance
time = 200

# Simulation loop
while distance < 1000 and speed >= 5:
    # Update time
    time += 1

    # Simulate random acceleration or deceleration
    acceleration = random.uniform(-max_deceleration_rate, max_acceleration_rate)
    speed += acceleration

    # Cap the speed at the maximum speed
    speed = min(speed, max_speed)

    # Calculate the distance covered in this time step
    distance_covered = speed

    # Update distance
    distance += distance_covered

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

# Check for stopping condition
if distance >= 1000:
    print("Car covered 1000 meters.")
else:
    print("Car slowed down to below 5 m/s.")

Final Speed: 56.89 m/s
Distance Covered: 1018.11 meters
Time Taken: 219 seconds
Car covered 1000 meters.