需要帮助在R中为赌场玩家创建循环

时间:2016-06-27 16:00:20

标签: r

我在创建一个包含以大写字母1开头的casinoplayer的循环时遇到了问题。 她在赌场玩X次,直到她到达首都5或0。 我需要进行1000次模拟。 如果我想看看当她从资本2开始时结果如何变化,那只是改变资本< - 2。

到目前为止,我的代码看起来像这样。牛=获胜的机会

cow <- 0.5 if (runif(1) < cow) { capital <- 1 capital <- capital + 1 } else { capital <- capital - 1 }

谢谢!

2 个答案:

答案 0 :(得分:0)

我最近做了一些非常相似的事情(不是赌博,而是篮球射击练习 - 这个想法是一样的)。看看下面的代码。

'赌博'功能一次玩游戏,直到资本达到0或5,并记录你是赢还是输。它返回一个数据框,其中包含游戏结果,制作的赌博数量以及赢得的赌博百分比(从长远来看,这应该非常接近您赢得一轮的概率)。

'simulate.games'功能然后模拟这个游戏一千次。如果你想修改每轮中一个的数量,你可以在while循环中简单地修改'plus'和'minus'变量。

希望这有帮助!

library(dplyr)

gamble <- function(upper = 5, lower = 0, plus = 1, minus = -1, prob = .5) {
    # prob represents the probability of winning one round

    capital <- 1
    won <- 0
    count <- 0
    while(capital > lower & capital < upper){
        count <- count + 1
        game <- sample(x = c(plus, minus), size = 1, prob = c(prob, 1 - prob))
        capital <- capital + game
        if(game == plus){
            won <- won + 1
            }
        }
    result <- ifelse(capital <= lower, 0, 1) # 0 represents a loss, 1 represents a victory
    tbl_df(data.frame(result = result, count = count, pct = won / count))
}

simulate.games <- function(num.games = 1000, ...) {
    # initialize
    outcome <- gamble(...)
    for(i in 1:(num.games-1)){
        outcome <- rbind(outcome, gamble(...))
    }
    outcome
}

# typical usage:
# simulate.games(num.games = 1000, upper = 5, lower = 0, plus = 1, minus = -1, prob = .5)

答案 1 :(得分:0)

我试着做点什么:

#Here you have the definition of the function

gamble <- function(capital, upper=5, lower=0, cow=0.5){
  while(capital < upper & capital>lower){
    if(runif(1)>cow){
        capital <- capital +1
    } else capital <- capital -1
  }
  capital
}

# Here you have the call to the function and the cycle 

simulations <- 1000 # declare here the number of simulations
results <- c(1:simulations)
for(i in seq_along(results)){
   results[i] <- gamble(1)
}

结果('结果')是一个数字向量,包含每个模拟结束时的大写值(0或5)。希望这有帮助