# R code not working as it should? [closed]

I wanted to show computationally that if $$2$$ poker players are playing heads-up (1 vs. 1) and going all-in on coin flips, then a player with $$X\%$$ of the chips would win $$X\%$$ of the time.

However when I ran the following code, which should end up with a vector of the winners, "a" should have won $$68\%$$. However every simulation results in about $$55\%$$ or so:

set.seed(1000)
winner <- function(a, b){
win = 0
while (win == 0){
p <- runif(1, 0, 1)
if(p > 0.5){
if(a >= b){
winner = "a"
win = 1
} else {
a <- 2*a
b <- b - a
}
} else {
if(a <= b){
winner = "b"
win = 1
} else {
b <- 2*b
a <- a - b
}
}
}
return(winner)
}

winners <- c()
for (i in 1:1000){
winners <- c(winners, winner(17, 8))
}
17/25
sum(winners == "a")/length(winners)


I am positive I have made a mistake somewhere in the code. I am confident that the maths in right. Just wondering where it is that I've messed up.

Many thanks.

• Please show the maths so we can see the assumptions. Jan 28, 2019 at 11:38

The error is here:

    a <- 2*a
b <- b - a


and here:

   b <- 2*b
a <- a - b


You are first doubling the winner's account and then substracting the loss. Hence, the player who lost loses twice as much as he should have lost. Change the order of these lines in both cases (a wins or b wins), then you will get the expected probabilities.

• Been a while since I've done this style of coding. Well spotted. Thank you Jan 28, 2019 at 15:09