【问题标题】:Monte Carlo Dice Simulation in RR中的蒙特卡洛骰子模拟
【发布时间】:2016-08-19 17:23:32
【问题描述】:

您好,我正在尝试解决一个玩家有 10 美元的问题。掷硬币,如果玩家正确地叫它,他赚 1 美元,如果他不正确,他输 1 美元。他在达到 20 美元之前达到 0 美元的几率是多少?游戏平均持续多长时间? 25次翻转后他平均有多少?我应该在 R 中使用蒙特卡洛方法来编写代码,但我是一个初学者,不完全确定从哪里开始——这就是我的想法

game <- function() {
x=10 ## $10
y=0 ## number of times player gets $20
z =0 ## number of times player loses money
 result<- sample(1:2,1, replace = TRUE)
if (result==1) {
x=x+1 } ## money goes up, 1 represents player calling correct coin
else{
x=x-1 }
if (x= 20) { 
y = y+1} ### dont know how to stop trials
if(x=0){
z=z+1}

我对如何编写代码很迷茫,但这是一个想法。基本上我想模拟一个 50/50 的模拟,看看 y 和 z 出现的频率。我不确定如何运行一定数量的试验或在达到 20 或 0 时停止....感谢您的帮助。

【问题讨论】:

    标签: r simulation probability montecarlo dice


    【解决方案1】:

    啊,Gambler's Ruin 的一个版本。

    无论如何,您似乎还没有在 R 中使用循环(如 forwhile),这很奇怪,因为这学期还很远。

    以下内容将使您能够运行模拟来回答您的问题。

    # Set configuration
    money = 10  # $10
    
    B = 100         # Number of games to play
    
    y = 0           # Number of times player gets $20 from ALL games run
    z = rep(0, B)   # Number of times player loses money per game
    r = rep(0, B)   # Number of rounds played per game
    a = rep(0, B)   # Value on the 25th turn per game (not the average!)
    
    # Start playing games!
    for(i in 1:B){
    
      # Reset settings for each game. 
    
      # Make it reproducible by setting a seed. 
      set.seed(1337+i)
    
      # Set Counter
      count = 1
    
      # Set game
      x = money
    
      while( x > 0 ){
    
        # Perform the draw
        result = sample(1:2,1, replace = TRUE)
    
        # 1 means the player wins!
        if(result == 1) {
          x = x + 1 
    
        } else { # 2 - The player loses!
          x = x - 1 
    
          # Increment Player Loss
          z[i] = z[i] + 1
        }
    
        # Increase round calculation
        r[i] = r[i] + 1
    
        count = count + 1
    
        # After 25 flips, how much is left? 
        if(count == 25){
          a[i] = x
        }
    
        # Reset to zero? 
        if(x == 20){
          y = y + 1
    
          # End game
          break;
        }
    
      }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-24
      • 1970-01-01
      • 2021-01-06
      • 1970-01-01
      • 1970-01-01
      • 2023-03-05
      • 2018-04-03
      • 2020-08-25
      相关资源
      最近更新 更多