[1] 4
[1] 3.4973
[1] 3.4769
[1] 3.4792
DATA 352/551: Modeling and Simulation
Input: parameters of the ONE simulation Output: a single result (i.e., “what do you want to save after ONE simulation?”)
Test the function with a few calls to make sure it works as expected
Initialize global simulation parameters
How many simulations do you want to run? How should the results be stored? Important: should always pre-allocate a vector (e.g.
rep(NA, 10000)) to store results, rather than appending to a vector each time
Can use a
forloop, or functional wrappers likereplicate()(in R), or functions that can handle parallelization (i.e., use multiple cores on your computer to run simulations faster)
What is the expected value of the outcome of a fair die? Design and implement a simulation to find out.
[1] 4
[1] 3.4973
[1] 3.4769
[1] 3.4792
Note: Method 1 and Method 2 are computational similar (provided that the result vector is pre-allocated). Method 3 is more advanced and can be significantly faster for very large simulations.
An R function is a named piece of code that takes inputs, does some work, and returns an output.
Give the function a descriptive name.
Put the inputs in the parentheses, with defaults when useful.
Write the calculation inside the braces.
The last expression is returned automatically; return() is optional.
To return more than one value, you can put the values in a list.
Basic example 1:
double_value(x): return twice the value of x.celsius_to_fahrenheit(celsius): convert a temperature using \(F = 32 + 9C/5\).roll_die(n = 6): simulate one roll of a fair die with n sides.mean_of_two(x, y): return the average of two numbers.[1] 8
[1] 68
[1] 1
[1] 11
[1] 5
An if statement allows you to run a chunk of code only when a condition is true. It is often used together with loops.
Basic structure in R:
You might need multiple if statements to cover more than one condition. You can also use an else statement.
Example: We roll a fair die. If the outcome is 6, we win $20; if the outcome is 4 or 5, we win $10; otherwise we lose $15. Is this a fair game? How much would you expect to win or lose? Write a function to play this game one time.
[1] -15
[1] -1.0375
For comparison, the expected value is
\[ E[X] = \frac{1}{6}(20) + \frac{2}{6}(10) + \frac{3}{6}(-15) = \frac{20 + 20 - 45}{6} = -\frac{5}{6} \approx -0.83. \]
So this is not a fair game: on average, you lose about $0.83 in the long run.
Loops are used to repeat a chunk of code.
for loop: repeat a fixed number of timeswhile loop: repeat until a condition is metBasic example:
for loop has an index and a code chunk. For example, if the index is \(i = 1, 2, 5\), then the code chunk runs with \(i = 1\), then with \(i = 2\), and then with \(i = 5\). The index (i in the above example) does not need to be created separately.Exercise: “fake coding”
weighCat() and store the weight in a vector.# 1. Repeat a task 10 times
for (i in 1:10) {
perform_task()
}
# 2. Repeat a simulation 1000 times and store each result
results <- rep(NA, 1000)
for (i in 1:1000) {
results[i] <- run_one_simulation()
}
# 3. Weigh every 3rd cat and store the weights
weights <- rep(NA, 1000/3)
result_index <- 1
for (cat_index in seq(3, 999, by = 3)) {
weights[result_index] <- weighCat(cats[cat_index])
result_index <- result_index + 1
}
# 4. Weigh and store the female cats
female_weights <- rep(NA, 1000)
result_index <- 1
for (cat_index in 1:1000) {
if (cats$sex[cat_index] == "female") {
female_weights[result_index] <- weighCat(cats[cat_index])
result_index <- result_index + 1
}
}Exercise: Use any language and loop structures to do the following.
for (moose in 1:30) {
cat(moose, "moose", 4 * moose, "legs\n")
}
net <- 0
bet <- 1
for(i in 1:10){
roll <- sample(x = c('W','L'),
size = 1,
prob = c(0.48,0.52))
if(roll == "W"){
net <- net + bet
bet <- 1
}
if(roll == "L"){
net <- net - bet
bet <- 2*bet
}
print(paste('game',i,'||result',roll,'||next bet',bet,'||net',net))
}Basic example:
A while loop has three ingredients:
The code runs as long as the condition is met. This is useful when the number of repetitions is not known in advance.
Exercise: “fake coding”
# 1. Play until the net winnings reach $5
net_winnings <- 0
number_of_plays <- 0
maximum_number_of_plays <- 10000
while (net_winnings < 5 & number_of_plays < maximum_number_of_plays) {
# update net_winnings and number_of_plays
}
# 2. Play until winning $5 or losing $100
net_winnings <- 0
number_of_plays <- 0
maximum_number_of_plays <- 10000
while (net_winnings < 5 & net_winnings > -100 & number_of_plays < maximum_number_of_plays) {
# update net_winnings and number_of_plays
}Exercise: Use any language and loop structures to do the following.
net <- 0
bet <- 1
counter <- 1
while ((net < 5) & (net > -100) & counter < 10000) {
roll <- sample(x = c("W", "L"),
size = 1,
prob = c(0.48, 0.52))
if (roll == "W") {
net <- net + bet
bet <- 1
}
if (roll == "L") {
net <- net - bet
bet <- 2 * bet
}
counter <- counter + 1
print(paste("game", counter,
"||result", roll,
"||next bet", bet,
"||net", net))
}simulate_martingale <- function(win_probability = 0.48,
win_target = 5,
loss_limit = -100,
maximum_games = 10000) {
net <- 0
bet <- 1
counter <- 1
while ((net < win_target) &
(net > loss_limit) &
counter < maximum_games) {
roll <- sample(x = c("W", "L"),
size = 1,
prob = c(win_probability, 1 - win_probability))
if (roll == "W") {
net <- net + bet
bet <- 1
}
if (roll == "L") {
net <- net - bet
bet <- 2 * bet
}
counter <- counter + 1
print(paste("game", counter,
"||result", roll,
"||next bet", bet,
"||net", net))
}
return(list(net = net, games = counter - 1, next_bet = bet))
}
simulate_martingale()The function takes the winning probability, stopping targets, and maximum number of games as inputs. It returns the final net winnings, number of games played, and next betting value.