赌博算法

AK9*_*309 1 r gambling

我很难弄清楚如何用 R 编写程序。我想在红色上下注 1 美元,如果我赢了,我会得到 1 美元并再次下注,如果我输了,我会加倍下注。该程序应该运行直到我赢了 10 美元或赌注大于 100。这是我的代码:

    W=0
    B=1

    for(i=sample(0:1,1)){
      B<-1
      W<-0
      while(W<10 & B<=100){
        if(i=1){
          W<-W+B 
          B<-B
        }else{
          B<-2*B
        }
        print(B)
      }
    }
Run Code Online (Sandbox Code Playgroud)

i决定我是输还是赢。我print(B)用来查看程序是否运行。在这一点上它没有,无论如何 B 都等于 1。

ins*_*ven 5

为了使这种赌博的后果更加明显,我们可以修改这个程序,添加变量来存储总赢/输和这个数字的动态。

W_dyn <- c()      # will store cumulative Win/Lose dynamics
W. <- 0           # total sum of Win/Lose        
step <- 0         # number of bet round - a cycle of bets till one of 
                  # conditions to stop happen:   W > 10 or B >= 100
while (abs(W.) < 1000)
{ B <- 1
  while (W < 10 & B <= 100)
  { i <- sample(0:1, 1)
    if (i == 1)
    { W <- W + B 
      B <- 1
    } else
    { W <- W - B
      B <- 2 * B
    } 
    print(B)
  }
  W. <- W. + W
  W <- 0
  step <- step + 1
  W_dyn[step] <- W.
  cat("we have", W., "after", step, "bet rounds\n")
}
# then we can visualize our way to wealth or poverty
plot(W_dyn, type = "l")
Run Code Online (Sandbox Code Playgroud)

厄运! :( 这是我的一天! :)

顺便说一句,在最大可能的条件下,B < Inf这种赌博从长远来看总是浪费金钱。