跟踪循环迭代 [英] Track loop iterations

查看:32
本文介绍了跟踪循环迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

抛硬币.成功,你赢了 100,否则你输了 50.你会一直玩下去,直到你口袋里有钱a.a 在任何迭代中的值如何存储?

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
  }
}

作为最终结果,当 while 循环结束时,我希望能够查看每次迭代的 a 的值,而不仅仅是最终的结果.我查阅了关于 计算 sapply 中的迭代 的帖子,但我无法把它应用到这个案例中.

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.

推荐答案

a 的初始值存储在第二个向量中,并将 a 的新值附加到每次迭代.

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))]

但不能保证您会在 n 次迭代中用完钱(在这种情况下,您会收到错误,只需查看 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).

编辑

针对@Roland 表达的担忧,以下方法可避免重新分配每次迭代的内存:

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)]

这篇关于跟踪循环迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆