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}))
Number of Heads: 516
Number of Tails: 484
Heads Probability: {0.516}
Tails Probability: {0.484}

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)

print("Die1 is:", Die1)
print("Die2 is:", Die2)

print(Die1 + Die2)
#Code, Code, Code

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):
    height_dropped = input("Type in the height you would like the object to be dropped from")
    G = 9.81 
    sqrt((2 * height_dropped)/G)
    
print(simulation(3))

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

# Initialize variables
sessions_won = 0  # Counter for sessions won
jackpot_won = False  # Jackpot status

# Number of sessions to simulate
num_sessions = 10  # You can adjust this number

# Simulate the game for the specified number of sessions
for session in range(1):
    # Roll two dice
    dice_roll_1 = random.randint(1, 6)
    dice_roll_2 = random.randint(1, 6)
    total_roll = dice_roll_1 + dice_roll_2

    # Check if the session is won (dice roll >= 9)
    if total_roll >= 9:
        sessions_won += 1

    # Check if the jackpot is won (more than 5 sessions won)
    if sessions_won > 5:
        jackpot_won = True
        break  # No need to continue simulating

# Calculate the probability of hitting the jackpot
probability = sessions_won / num_sessions

# Output the results
print(f"Simulated {num_sessions} sessions.")
print(f"Sessions won: {sessions_won}")
if jackpot_won:
    print("Congratulations! You hit the jackpot!")
else:
    print("You didn't hit the jackpot this time.")
print(f"Probability of hitting the jackpot: {probability:.2%}")
       
Simulated 10 sessions.
Sessions won: 0
You didn't hit the jackpot this time.
Probability of hitting the jackpot: 0.00%

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 = 1
max_altitude = 42000  # Maximum altitude in feet
speed = 0
max_speed = 638  # Maximum speed in mph
fuel = 100  # Initial fuel in gallons

print("Welcome to Flight Simulator!")

# Simulate the flight
while altitude < 10000 and fuel > 0 and altitude > 0:
    # Simulate random changes in altitude, speed, and fuel
    altitude_change = random.randint(0, 500)  # Random altitude change (up to 500 feet)
    speed_change = random.randint(0, 20)  # Random speed change (up to 20 mph)
    fuel_consumption = random.randint(1, 5)  # Random fuel consumption (1 to 5 gallons)

    # Update altitude, speed, and fuel
    altitude += altitude_change
    speed += speed_change
    fuel -= fuel_consumption

    # Ensure altitude, speed, and fuel remain within realistic limits
    altitude = min(altitude, max_altitude)
    speed = min(speed, max_speed)
    fuel = max(fuel, 0)

    # Print the current status
    print(f"Altitude: {altitude} feet, Speed: {speed} mph, Fuel: {fuel} gallons")

# Check the flight outcome
if altitude >= 10000:
    print("Congratulations! You've reached 10,000 feet.")
elif altitude <= 0:
    print("Altitude dropped to 0. The flight is over.")
else:
    print("Out of fuel. The flight is over.")

Welcome to Flight Simulator!
Altitude: 373 feet, Speed: 2 mph, Fuel: 97 gallons
Altitude: 853 feet, Speed: 9 mph, Fuel: 96 gallons
Altitude: 1304 feet, Speed: 18 mph, Fuel: 93 gallons
Altitude: 1456 feet, Speed: 34 mph, Fuel: 91 gallons
Altitude: 1470 feet, Speed: 51 mph, Fuel: 87 gallons
Altitude: 1600 feet, Speed: 51 mph, Fuel: 86 gallons
Altitude: 1981 feet, Speed: 69 mph, Fuel: 85 gallons
Altitude: 2437 feet, Speed: 74 mph, Fuel: 80 gallons
Altitude: 2507 feet, Speed: 84 mph, Fuel: 78 gallons
Altitude: 2674 feet, Speed: 99 mph, Fuel: 74 gallons
Altitude: 3126 feet, Speed: 103 mph, Fuel: 70 gallons
Altitude: 3303 feet, Speed: 122 mph, Fuel: 68 gallons
Altitude: 3536 feet, Speed: 137 mph, Fuel: 66 gallons
Altitude: 3640 feet, Speed: 144 mph, Fuel: 63 gallons
Altitude: 4006 feet, Speed: 160 mph, Fuel: 60 gallons
Altitude: 4452 feet, Speed: 162 mph, Fuel: 55 gallons
Altitude: 4670 feet, Speed: 164 mph, Fuel: 54 gallons
Altitude: 4937 feet, Speed: 181 mph, Fuel: 52 gallons
Altitude: 5421 feet, Speed: 198 mph, Fuel: 51 gallons
Altitude: 5689 feet, Speed: 198 mph, Fuel: 49 gallons
Altitude: 5725 feet, Speed: 207 mph, Fuel: 45 gallons
Altitude: 6147 feet, Speed: 208 mph, Fuel: 41 gallons
Altitude: 6282 feet, Speed: 214 mph, Fuel: 40 gallons
Altitude: 6316 feet, Speed: 218 mph, Fuel: 35 gallons
Altitude: 6603 feet, Speed: 225 mph, Fuel: 30 gallons
Altitude: 6608 feet, Speed: 225 mph, Fuel: 26 gallons
Altitude: 7061 feet, Speed: 235 mph, Fuel: 25 gallons
Altitude: 7552 feet, Speed: 251 mph, Fuel: 22 gallons
Altitude: 7565 feet, Speed: 270 mph, Fuel: 20 gallons
Altitude: 7712 feet, Speed: 287 mph, Fuel: 15 gallons
Altitude: 7762 feet, Speed: 290 mph, Fuel: 13 gallons
Altitude: 8157 feet, Speed: 303 mph, Fuel: 9 gallons
Altitude: 8314 feet, Speed: 306 mph, Fuel: 8 gallons
Altitude: 8600 feet, Speed: 310 mph, Fuel: 7 gallons
Altitude: 8743 feet, Speed: 316 mph, Fuel: 3 gallons
Altitude: 8981 feet, Speed: 332 mph, Fuel: 0 gallons
Out of fuel. The flight is over.

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

# Initialize variables
starting_money = 100
sessions = 0
session_wins = 0
jackpot_wins = 0

# Number of sessions to simulate
num_sessions = 10

# Simulate the game for 10 sessions
while sessions < num_sessions:
    money = starting_money  # Reset money for each session

    money_change = 0

    for _ in range(1):  # You need to win at least 5 sessions to win the jackpot
        dice_roll = random.randint(1, 6) + random.randint(1, 6)

        if dice_roll <= 3:
            money_change = -70
            money += money_change
        if dice_roll > 3 and dice_roll < 6:
            money_change = -40
            money += money_change
        if dice_roll >= 6 and dice_roll < 9:
            money_change = 20
            money += money_change
        else:  # You win the session
            money_change = 50
            money += money_change
            session_wins += 1

        if money <= 0:
            break  # You ran out of money, end the session

        print(f"Session {sessions + 1}, Roll: {dice_roll}, Money Change: {money_change}, Total Money: {money}")

    if session_wins >= 5:
        jackpot_wins += 1

    sessions += 1

# Calculate the probability of hitting the jackpot
probability = jackpot_wins / num_sessions

print(f"Simulated {num_sessions} sessions.")
print(f"Probability of hitting the jackpot: {probability:.2%}")

Session 1, Roll: 10, Money Change: 50, Total Money: 150
Session 2, Roll: 6, Money Change: 20, Total Money: 120
Session 3, Roll: 9, Money Change: 50, Total Money: 150
Session 4, Roll: 11, Money Change: 50, Total Money: 150
Session 5, Roll: 2, Money Change: 50, Total Money: 80
Session 6, Roll: 2, Money Change: 50, Total Money: 80
Session 7, Roll: 6, Money Change: 20, Total Money: 120
Session 8, Roll: 2, Money Change: 50, Total Money: 80
Session 9, Roll: 3, Money Change: 50, Total Money: 80
Session 10, Roll: 4, Money Change: 50, Total Money: 110
Simulated 10 sessions.
Probability of hitting the jackpot: 50.00%

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 = 6  # 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

# Constants
target_distance = 1000  # Target distance in meters
min_speed = 5  # Minimum speed in m/s

# Simulation loop
while distance < target_distance and speed >= min_speed:
    # Update time
    time += 1

    # Accelerate until reaching maximum speed
    if speed < max_speed:
        speed += acceleration

    # Check if speed exceeds maximum
    if speed > max_speed:
        speed = max_speed

    # Update distance based on current speed
    distance += speed

    # Decelerate if necessary
    if distance >= target_distance:
        break
    if speed - deceleration > min_speed:
        speed -= deceleration
    else:
        speed = min_speed

# Output results
print("Final speed:", speed, "m/s")
print("Distance covered:", distance, "m")
print("Time taken:", time, "seconds")


#Code Code Code
Final speed: 45 m/s
Distance covered: 1007 m
Time taken: 38 seconds

Tangibles:

Nice to learn about simulations, since I don’t think we’ve really talkeda about them before. It was interesting to think about real-life situations and figure out solutions to these problems with code. The gambling one was especially interesting because so many people use die or coins to make micellaneous decisions. I think I learned a lot about manipulating variables and how to use the syntax for finding random values.