Track loop iterations

后端 未结 1 696
傲寒
傲寒 2021-01-25 21:20

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 it

1条回答
  •  梦毁少年i
    2021-01-25 22:26

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

    0 讨论(0)
提交回复
热议问题