Lecture 3: Implementing simulations

DATA 352/551: Modeling and Simulation

Example: outcome of a fair die

What is the expected value of the outcome of a fair die? Design and implement a simulation to find out.

# 1. ONE simulation function
sim_die <- function(n = 6) {
  return(sample(1:n,size=1))
}

# 2. Test the function
sim_die()
[1] 4
# 3. Initialize global simulation parameters
NSIM <- 10000
result <- rep(NA, NSIM)

# 4. Repeat the simulation NSIM times

#### Method 1: 'for' loop
for(i in 1:NSIM) {
  result[i] <- sim_die()
}
mean(result)
[1] 3.4973
#### Method 2: Base R replicate()
result <- replicate(NSIM, sim_die())
mean(result)
[1] 3.4769
#### Method 3: parallel processing (optional)
library(parallel)
cl <- makeCluster(2) # use 2 cores
clusterExport(cl, "sim_die")
result <- parSapply(cl, 1:NSIM, function(i) sim_die())
stopCluster(cl)
mean(result)
[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.

R review

Functions

An R function is a named piece of code that takes inputs, does some work, and returns an output.

function_name <- function(input1, input2 = default_value) {
  # code that uses the inputs to generate result
  return(result)
}
  • 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:

square_plus_one <- function(x) {
  return(x^2 + 1)
}

square_plus_one(3)
# 10
  • Basic example 2:
summarize_values <- function(first_value, second_value, third_value = 10) {
  result <- list(
    total = first_value + second_value + third_value,
    average = (first_value + second_value + third_value) / 3
  )
  return(result)
}

summarize_values(4, 8)
# $total
# [1] 22
#
# $average
# [1] 7.333333
  • Exercise: write and test a function for each task
  1. double_value(x): return twice the value of x.
  2. celsius_to_fahrenheit(celsius): convert a temperature using \(F = 32 + 9C/5\).
  3. roll_die(n = 6): simulate one roll of a fair die with n sides.
  4. mean_of_two(x, y): return the average of two numbers.
Show solution
double_value <- function(x) {
  result <- 2 * x
  return(result)
}

result <- double_value(4)
result
[1] 8
temperature <- function(celsius) {
  result <- 32 + 9 * celsius / 5
  return(result)
}
temperature(20)
[1] 68
roll_die <- function(n = 6) {
  result <- sample(1:n, size = 1)
  return(result)
}

roll_die()
[1] 1
roll_die(20)
[1] 11
mean_of_two <- function(x, y) {
  result <- (x + y) / 2
  return(result)
}

mean_of_two(3, 7)
[1] 5

If statements

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:

if (condition) {
  # code to run when the condition is TRUE
}

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.

Show solution
play_game <- function() {
  outcome <- sample(1:6, size = 1)

  if (outcome == 6) {
    result <- 20
  } else if (outcome %in% c(4, 5)) {
    result <- 10
  } else {
    result <- -15
  }

  return(result)
}

# One play
play_game()
[1] -15
# Approximate expected value by simulating many plays
NSIM <- 10000
result <- rep(NA, NSIM)
result <- replicate(NSIM, play_game())
mean(result)
[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

Loops are used to repeat a chunk of code.

  • for loop: repeat a fixed number of times
  • while loop: repeat until a condition is met

For loops

Basic example:

for (i in 1:5) {
  print(i)
}
  • A 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”

  1. Repeat a task 10 times.
  2. Repeat a simulation 1000 times and store the result each time.
  3. Suppose there is a large dataset of 1000 cats. Extract the 3rd, 6th, 9th, … cats from the dataset; for each cat, run a function weighCat() and store the weight in a vector.
  4. In a large dataset of cats, weigh and store the weights of the female cats.
Show solution
# 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.

  1. Print a sequence of texts: “1 moose 4 legs”, “2 moose 8 legs”, …, “30 moose 120 legs”.
  2. Simulate the Martingale doubling system` (Homework 1) 10 times. Start the betting amount at $1; if you win, you bet $1; if you lose, you double your bet. Assume a winning probability of \(0.48\). For each of the 10 simulated games, print the game result (W or L), the current net winnings, and the current betting value.
Show solution
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))
}

While loops

Basic example:

x <- 1
while (x < 5) {
  print(x)
  x <- x + 1
}

A while loop has three ingredients:

  • initialization
  • condition
  • code chunk that updates the condition

The code runs as long as the condition is met. This is useful when the number of repetitions is not known in advance.

  • It is important to properly update the objects involved in the while-loop condition.
  • It is also recommended to set a safety upper bound so the loop cannot run forever.
x <- 0
count <- 0
while (x < 5 && count < 1000) {
  x <- x + 1
  count <- count + 1
}

Exercise: “fake coding”

  1. Play a game until you win \(5\).
  2. Play a game until you win \(5\) or lose \(100\).
Show solution
# 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.

  1. Simulate the Martingale doubling system until you win \(5\) or lose \(100\). Start the betting amount at \(1\); if you win, you bet \(1\); if you lose, you double your bet. Assume a winning probability of \(0.48\). For each simulated game, print the game result (W or L), the current net winnings, and the current betting value.
  2. Write an R function to perform the above simulation. Carefully design the inputs and outputs of the function.
Show solution: one simulation
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))
}
Show solution: simulation function
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.