问题
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 money to bet or have bet 100 times. I then have to do the martingale simulation 100 times. When I apply my code, I get the following errors;
Error: unexpected '}' in "}" (I think all brackets are accounted for)
Error in martingale_function(m, c, n, p) : could not find function "martingale_function"
(I don't know why I get this error)
m = amount to bet
c = initial bet
n= number of round
p = probability of winning
martingale_function <- function(m,c,n,p){
for(i in 1:n){
betting_money <- m
amount_bet <- c
end_Sim <- FALSE
while(!end_Sim){
if(runif(1) = p){
betting_money <- betting_money + amount_bet
amount_bet <- amount_bet
}
else {
betting_money <- betting_money - amount_bet
amount_bet <- amount_bet*2
}
if(betting_money <= 0|i=100){# if we have no more money left to bet or have done it 100 times we stop
end_Sim <- TRUE
}
} return(betting_money)
}
}
iteration_function <- function(m,c,n,p){
for(i in 1:100){
return(data.frame(Iteriation=i,AmountLeft = martingale_function(m,c,n,p)))
}
}
iteration_function(650,5,100,18/38)
回答1:
Errors:
- Line 13: shouldn't be
runif(1) = p
, perhaps you meantrunif(1) < p
? - Line 15: I suspect you meant
amount_bet <- c
instead ofamount_bet <- amount_bet
- Line 21: should be
i==100
noti=100
- Line 26:
}
should be moved beforereturn()
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)
}
回答2:
Check out the line where you write:
if(runif(1) = p){}
Shouldn't that be a double equals sign?
来源:https://stackoverflow.com/questions/51596733/r-help-for-martingale-simulation