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
Errors:
runif(1) = p
, perhaps you meant runif(1) < p
?amount_bet <- c
instead of amount_bet <- amount_bet
i==100
not i=100
}
should be moved before return()
lineThings that don't affect execution of code, but should be changed:
} else {
one one linereturn()
to its own lineAlso, 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)
}