2016-04-26 131 views
1

嗨我試圖解決一個球員有$ 10的問題。一個硬幣被翻轉,如果玩家正確地稱它爲$ 1,如果他不正確,他將失去$ 1。他在達到20美元之前會達到0美元的機率是多少?遊戲持續時間平均多久?在25次翻轉後,他平均有多少錢?我應該使用蒙特卡洛方法中的R爲這個代碼,但我是一個初學者,不能完全確定在這裏start--就是我的想法R的蒙特卡羅骰子模擬

game <- function() { 
x=10 ## $10 
y=0 ## number of times player gets $20 
z =0 ## number of times player loses money 
result<- sample(1:2,1, replace = TRUE) 
if (result==1) { 
x=x+1 } ## money goes up, 1 represents player calling correct coin 
else{ 
x=x-1 } 
if (x= 20) { 
y = y+1} ### dont know how to stop trials 
if(x=0){ 
z=z+1} 

我很失去了對如何編寫代碼這但是這是一個想法。基本上我想模擬一個50/50模擬,看看y發生和z發生的頻率。我不知道如何運行一定數量的試驗或停止當我達到20或0 ....感謝您的任何幫助。

回答

1

啊,Gambler's Ruin的一個版本。

無論如何,看起來好像你還沒有在R中使用循環(如forwhile),這很奇怪,因爲它在這個學期相當遙遠。

以下將使您能夠運行模擬來回答您的問題。

# Set configuration 
money = 10 # $10 

B = 100   # Number of games to play 

y = 0   # Number of times player gets $20 from ALL games run 
z = rep(0, B) # Number of times player loses money per game 
r = rep(0, B) # Number of rounds played per game 
a = rep(0, B) # Value on the 25th turn per game (not the average!) 

# Start playing games! 
for(i in 1:B){ 

    # Reset settings for each game. 

    # Make it reproducible by setting a seed. 
    set.seed(1337+i) 

    # Set Counter 
    count = 1 

    # Set game 
    x = money 

    while(x > 0){ 

    # Perform the draw 
    result = sample(1:2,1, replace = TRUE) 

    # 1 means the player wins! 
    if(result == 1) { 
     x = x + 1 

    } else { # 2 - The player loses! 
     x = x - 1 

     # Increment Player Loss 
     z[i] = z[i] + 1 
    } 

    # Increase round calculation 
    r[i] = r[i] + 1 

    count = count + 1 

    # After 25 flips, how much is left? 
    if(count == 25){ 
     a[i] = x 
    } 

    # Reset to zero? 
    if(x == 20){ 
     y = y + 1 

     # End game 
     break; 
    } 

    } 

}