R Help For Martingale Simulation

前端 未结 2 882
遇见更好的自我
遇见更好的自我 2021-01-27 20:53

I\'m trying to make a martingale simulation in R where I bet an amount and if I win I bet the same amount but if I lose, I bet double the amount. I do this until I run out of mo

2条回答
  •  醉话见心
    2021-01-27 21:43

    Errors:

    • Line 13: shouldn't be runif(1) = p, perhaps you meant runif(1) < p?
    • Line 15: I suspect you meant amount_bet <- c instead of amount_bet <- amount_bet
    • Line 21: should be i==100 not i=100
    • Line 26: } should be moved before return() line

    Things that don't affect execution of code, but should be changed:

    • Line 16: it's good programming practice to write } else { one one line
    • Line 24: you should move return() to its own line

    Also, I'm not sure why there are two for loops. It seems like you only need one.


    Here's my re-write of your code (with some assumptions about exactly what you're trying to do):

    # write betting function
    martingale <- function(m, c, p) {
        money   <- m
        betsize <- c
        i <- 1
        while(money > 0 & i <= 100) {
            if(runif(1) < p) {
                money <- money + betsize
                betsize <- c
            } else {
                money <- money - betsize
                betsize <- betsize * 2
            }
            i <- i + 1
        }
        return(money)
    }
    
    # run it 100 times
    n <- 100
    res_df <- data.frame(iteration = rep(NA_integer_, n), amountleft = rep(NA_real_, n))
    for (i in 1:n) {
        res_df[i , "iteration"]  <- i
        res_df[i , "amountleft"] <- martingale(m=650, c=5, p=18/38)
    }
    

提交回复
热议问题