R中的蒙特卡罗骰子模拟

时间:2016-04-26 04:50:28

标签: r simulation probability montecarlo dice

您好我正在尝试解决玩家有10美元的问题。硬币被翻转,如果玩家正确地称它为1美元,如果他不正确他会损失1美元。在他达到20美元之前,他将达到0美元的几率是多少?游戏的平均持续时间有多长? 25次翻转后平均他有多少钱?我应该在R中使用蒙特卡罗方法对此进行编码,但我是初学者,并不完全确定从哪里开始 - 这就是我的想法

DECLARE @Range AS INT = 1000;

WITH E1(N) AS( -- 10 ^ 1 = 10 rows
    SELECT 1 FROM(VALUES (1),(1),(1),(1),(1),(1),(1),(1),(1),(1))t(N)
),
E2(N) AS(SELECT 1 FROM E1 a CROSS JOIN E1 b), -- 10 ^ 2 = 100 rows
E4(N) AS(SELECT 1 FROM E2 a CROSS JOIN E2 b), -- 10 ^ 4 = 10,000 rows
CteTally(GOAL_VERSION_NO) AS(
    SELECT TOP(@Range) ROW_NUMBER() OVER(ORDER BY(SELECT NULL))
    FROM E4
)
SELECT
    tbl.*,
    y.GOAL_VERSION_NO
FROM EVALGOAL_GROUP_EMP AS tbl
CROSS JOIN CteTally y

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

1 个答案:

答案 0 :(得分: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;
    }

  }

}