# HW2 請寫出一個function,模擬一個簡單的賭博遊戲,擲兩個骰子,點數為 1 到 6,並算出期望值。 ## 程式內容 最後需交出一個 function 叫 craps_game , 該function有兩個輸入:num_simulations (the number of simulations to run) 和 bet_size (the size of the bet for each game)。function裡為模擬此賭博遊戲的輸贏。 此賭博遊戲為,用sample()去模擬擲兩個骰子。加總擲出的兩個骰子數字,為點數和。 如果第一次點數和為 7 或 11,玩家勝,贏得 bet size 。 若點數和為 2、3 或 12,玩家輸,輸了 -1 x bet size。如果點數和為其他點數,記錄第一次的點數和,然後繼續擲骰,直至點數和等於第一次擲出的點數和,玩家勝,贏得 bet size。若在這之前擲出了點數和為 7,玩家輸,輸了 -1 x bet size。 計算遊戲的期望值 expected value = (probability of winning x bet size) + (probability of losing x -bet size). craps_game function 輸出(Return) 遊戲的期望值。 ```R # 骰子的函數 roll_dice <- function() { return(sample(1:6, 2, replace = TRUE)) } # 定義玩一次的遊戲函數 play_once <- function() { dice_sum <- sum(roll_dice()) if (dice_sum %in% c(7, 11)) { return(TRUE) # 玩家勝 } else if (dice_sum %in% c(2, 3, 12)) { return(FALSE) # 玩家輸 } else { # 紀錄第一次的點數和 point <- dice_sum # 持續擲骰直至點數和等於第一次擲出的點數和或擲出 7 repeat { new_dice_sum <- sum(roll_dice()) if (new_dice_sum == point) { return(TRUE) # 玩家勝 } else if (new_dice_sum == 7) { return(FALSE) # 玩家輸 } } } } # 定義 craps_game 函數 craps_game <- function(num_simulations, bet_size) { win <- 0 for (i in 1:num_simulations) { if (play_once()) { win <- win + 1 } } # 計算勝率和期望值 win_probability <- win / num_simulations expected_value <- (win_probability * bet_size) + ((1 - win_probability) * -bet_size) return(expected_value) } ``` ## 2. 測試程式與結果 ```R set.seed(123) num_simulations <- 6000 bet_size <- 10 result <- craps_game(num_simulations, bet_size) result ``` 輸出結果: ![image](https://hackmd.io/_uploads/rkkJlh1V6.png)