2016-04-27 133 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