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

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

random_int1 = random.randint(1, 6)
random_int2 = random.randint(1, 6)

sum = random_int1 + random_int2

print("First number is:", random_int1)
print("Second number is:", random_int2)
print("The sum of the numbers is:", sum)
First number is: 5
Second number is: 4
The sum of the numbers is: 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

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 

def simulation(height_dropped):
    time = (2 * height_dropped / G) ** 0.5
    
    return time

user_input = input("Enter a value for 'i': ") 
i = int(user_input)  
result = simulation(i) 
print(result)  


1.0096375546923044

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 

score = 0

for i in range (0, 10):
    random_int1 = random.randint(1, 6)
    random_int2 = random.randint(1, 6)
    sum = random_int1 + random_int2
    print("The sum of your", i+1, "roll is:", sum)
    if sum >= 9:
        score = score + 1
        
print("Your score is:", score)

if score >= 5:
    print("You win!")
else: 
    print("You lose!")
The sum of your 1 roll is: 8
The sum of your 2 roll is: 7
The sum of your 3 roll is: 6
The sum of your 4 roll is: 7
The sum of your 5 roll is: 11
The sum of your 6 roll is: 3
The sum of your 7 roll is: 7
The sum of your 8 roll is: 6
The sum of your 9 roll is: 5
The sum of your 10 roll is: 10
Your score is: 2
You lose!

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

print("Welcome to Flight Simulator!")

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

print("Starting Altitude:", altitude)
print("Starting Speed:", speed)
print("Starting Fuel:", fuel)

while altitude < 3000 and fuel > 0:
    speed = speed + 200
    altitude = altitude + speed
    fuel = fuel - 5
    
while altitude < 10000 and fuel > 0:
    altitude = altitude + speed
    fuel = fuel - 5

print("Final Altitude:", altitude)
print("Final Speed:", speed)
print("Final Fuel:", fuel)

print("The flight is over!")
# Code Code Code
Welcome to Flight Simulator!
Starting Altitude: 0
Starting Speed: 0
Starting Fuel: 100
Final Altitude: 10000
Final Speed: 1000
Final Fuel: 40
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

# Code Code Code

import random 

score = 0
money = 0

for i in range (0, 10):
    random_int1 = random.randint(1, 6)
    random_int2 = random.randint(1, 6)
    sum = random_int1 + random_int2
    print("The sum of roll number", i+1, "is", sum)
    if sum <= 3:
        money = money - 70
        print("You lost $70!")
    elif 3 < sum < 6:
        money = money - 40
        print("You lost $40!")
    elif 6 <= sum < 9:
        money = money + 20
        print("You won $20!")
    elif sum >= 9:
        money = money + 50
        print("You won $50!")
    if score >= 5:
        print("Jackpot! You won $100!")
        money = money + 100
        
        
print("Your profit: $", money)

    
    

The sum of roll number 1 is 10
You won $50!
The sum of roll number 2 is 3
You lost $70!
The sum of roll number 3 is 7
You won $20!
The sum of roll number 4 is 9
You won $50!
The sum of roll number 5 is 8
You won $20!
The sum of roll number 6 is 7
You won $20!
The sum of roll number 7 is 8
You won $20!
The sum of roll number 8 is 9
You won $50!
The sum of roll number 9 is 10
You won $50!
The sum of roll number 10 is 7
You won $20!
Your profit: $ 230

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


while speed < 60 and distance < 1000:
    speed = speed + acceleration
    time = time + 1
    distance = distance + speed
    if distance > 1000:
        distance = 1000
        break
    if speed > 60:
        speed = 60

while speed > 5 and distance < 1000:
    speed = speed - deceleration
    time = time + 1
    distance = distance + speed
    if distance > 1000:
        distance = 1000
        break
    if speed < 5:
        speed = 5
        print("The car has stopped after traveling", distance, "meters in", time, "seconds.")
        break

print("Time taken:", time, "seconds")
print("Final distance:", distance, "m")
print("Final Speed:", speed, "m/s")

Time taken: 32 seconds
Final distance: 1000 m
Final Speed: 58 m/s