2016-04-27 132 views
1

我必須在R中創建蒙特卡洛模擬。我模擬連續滾動一對骰子100次。我應該看到何時總共發生七次的第一次滾動。當第一個總數爲7的滾動滾動時,我想存儲這個數字,然後找到平均值。我將運行模擬10萬次,然後使用平均值來查看擲骰子總共需要多長時間才能完成7次。我無法存儲此值。這裏是一些peuedocode:For R循環存儲值

set.seed(101) 
trials<-4 ## will later change to 100,000 
for(j in 1:trials){ 
n=0 ## number of rolls 
while(n<100){ 

n=n+1 
result<-sum(sample(1:6,2,replace=TRUE)) ## rolling the dice 

if(result==7) ## if sum is 7, print 

print(n) ### not sure how to store the n value 
      ##to an array which i can later average 

break 
} 

任何幫助,將不勝感激。謝謝

+0

把'trial < - 4'改爲'trial < - rep(NA,4)',然後在循環中使用'trials [j] < - n'。你的循環條件有'for(j in 1:length(trials))'。 – Gopala

+0

@Gopala for循環必須更改爲'for(j in 1:length(trials))'代碼才能工作。 –

+0

我確實說過,儘管在意識到需求改變後作爲快速編輯。 – Gopala

回答

1

理論上你可能需要超過100次試驗才能達到7的總和(這是不太可能發生,但仍然可能)。因此,它是更好地與while (TRUE)這樣使它:

set.seed(101) 

ntrials <- integer(1e+5) 

for (i in seq_along(ntrials)) { 

    n <- 0 

    # Roll the dices until the sum is 7. 
    while (TRUE) { 

    n <- n + 1 
    current.result <- sum(sample(1:6, 2, replace=T)) 
    if (current.result == 7) { 
     ntrials[i] <- n 
     break 
    } 
    } 
} 

必要試驗的數量將存儲在ntrials