简体   繁体   English

R中的蒙特卡罗骰子模拟

[英]Monte Carlo Dice Simulation in R

Hi I am trying to solve a problem where a player has $10.嗨,我正在尝试解决玩家有 10 美元的问题。 A coin is flipped, if the player calls it correctly he earns $1, if he is incorrect he loses $1.一枚硬币被翻转,如果玩家正确调用它他赚了 1 美元,如果他不正确他失去 1 美元。 What are the odds that he will reach $0 before he reaches $20?他在达到 20 美元之前达到 0 美元的几率是多少? How long on average does the game last?游戏平均持续多长时间? How much does he have on average after 25 flips? 25次翻转后他平均有多少? I am supposed to use a Monte Carlo Method in R to code for this, but I am a beginner and not totally sure where to start-- here's what i was thinking我应该在 R 中使用 Monte Carlo 方法来为此编码,但我是初学者,不完全确定从哪里开始——这就是我的想法

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}

I am pretty lost on how to code this but here is an idea.我对如何编码这个很迷茫,但这里有一个想法。 Basically i want to simulated a 50/50 simulation and see how often y occurs and z occurs.基本上我想模拟一个 50/50 的模拟,看看 y 出现的频率和 z 出现的频率。 I'm not sure how to run a certain number of trials or stop when i reach 20 or 0.... Thanks for any help.我不确定如何进行一定数量的试验或在达到 20 或 0 时停止......感谢您的帮助。

Ahh, a version of theGambler's Ruin .啊,赌徒废墟的一个版本。

Anyhow, it seems as if you have yet to use loops (like for and while ) in R, which is strange since it is quite far in the semester.无论如何,似乎您还没有在 R 中使用循环(如forwhile ),这很奇怪,因为它在学期中很远。

The below will enable you to run the simulation to answer your questions.以下内容将使您能够运行模拟来回答您的问题。

# 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;
    }

  }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM