Track loop iterations

三世轮回 提交于 2019-12-31 07:27:09

问题


Flip a coin. Success, you win 100, otherwise you lose 50. You will keep playing until you have money in your pocket a. How can the value of a at any iteration be stored?

a <- 100
while (a > 0) {
  if (rbinom(1, 1, 0.5) == 1) {
    a <- a + 100
  } else {
    a <- a - 50
  }
}

As a final result, when the while loop ends, I would like to be able to look at the value of a for each iteration, instead of just the final result. I consulted the post on Counting the iteration in sapply, but I wasn't able to apply it to this case.


回答1:


Store the initial value of a in a second vector, and append the new value of a at each iteration.

a <- pocket <- 100
while (a > 0) {
  if (rbinom(1, 1, 0.5) == 1) {
    a <- a + 100
  } else {
    a <- a - 50
  }
  pocket <- c(pocket, a)
}

Of course a vectorised approach may be more efficient, e.g.:

n <- 1000000
x <- c(100, sample(c(100, -50), n, replace=TRUE))
cumsum(x)[1:match(0, cumsum(x))]

But there's no guarantee you'll run out of money within n iterations (in which case you receive an error and can just look at x to see the realised trajectory).


EDIT

In response to concerns voiced by @Roland, the following approach avoids reallocation of memory at each iteration:

n <- 1e6
a <- rep(NA_integer_, n)
a[1] <- 100L # set initial value (integer)
i <- 1 # counter
while(a[i] > 0) {
  # first check whether our results will fit. If not, embiggenate `a`.
  if(i==length(a)) a <- c(a, rep(NA_integer_, n))
  if (rbinom(1, 1, 0.5) == 1) {
    a[i+1] <- a[i] + 100L
  } else {
    a[i+1] <- a[i] - 50L
  }
  i <- i + 1  
}
a[seq_len(i)]


来源:https://stackoverflow.com/questions/34583522/track-loop-iterations

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!