问题描述
我正在尝试在 R 中进行马丁格尔模拟,我下注一个金额,如果我赢了,我下注相同的金额,但如果我输了,我下注的金额翻倍.我一直这样做,直到我没钱下注或下注 100 次为止.然后我必须做 100 次鞅模拟.当我应用我的代码时,出现以下错误;
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;
错误:}"中出现意外的}"(我认为所有括号都已考虑在内)
martingale_function(m, c, n, p) 中的错误:找不到函数martingale_function"
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)
推荐答案
错误:
- 第 13 行:不应该是
runif(1) = p
,也许你的意思是runif(1) ?
- 第 15 行:我怀疑你的意思是
amount_bet 而不是
amount_bet
- 第 21 行:应该是
i==100
而不是i=100
- 第 26 行:
}
应该移到return()
行之前
- 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:
- 第 16 行:编写
} else {
一行一行是很好的编程习惯 - 第 24 行:您应该将
return()
移动到它自己的行
- Line 16: it's good programming practice to write
} else {
one one line - Line 24: you should move
return()
to its own line
另外,我不确定为什么有两个 for
循环.看来你只需要一个.
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)
}
这篇关于马丁格尔模拟的 R 帮助的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!