50:50 election result

I am currently working with RStudio for the first time and have a problem with the following task:

2 n people go to vote for the mayor, exactly n people vote for one of the two candidates. Use a simulation to approximate the probability of the following event: At no point during the count is the difference in votes between the two candidates greater than 2. Experiment with different values for n, for example 2,5,10 and 50 .

The following code is given:

#Vorbereitende Befehle
n <- 10
x <- sample(c(rep(1,n),rep(-1,n)),size=2*n)     #Simulation des Auszaehlens
x
cumsum(x)                                       #alle Partialsummen
min(cumsum(x))

#Lösen der Problemstellungen durch R=1000 (oder mehr) Durchlaeufe
R <- 10000                                      #R Wiederholungen
erg <- rep(0,R)                                 #Abspeichern ob Bedingung erfuellt oder nicht
n <- 1000
for(i in 1:R){
  x <- sample(c(rep(1,n),rep(-1,n)),size=2*n)
  if(min(cumsum(x))>=0){erg[i] <- 1}            #falls Bedingung erfüllt kommt 1 in Vektor
}
mean(erg)                                       #Prozentsatz (=Schaetzung fuer Wahrscheinlichkeit)

In the script, the result for 2 is approx. 0.09 and for 50 approx. 0.0196 - I always get different results even with the same n?

I think there's something fundamental about the way Rstudio works that I haven't understood yet - but I can't figure it out!

Add set.seed(123)(or any other integer) to the start of the script to get the same results each time.

If you change the seed different random numbers will be generated and you'll get (slightly) different results.

1 Like

Hi martin.R,
Thanks for your reply, but unfortunately that doesn't solve my problem yet. For n=50 I should get the value 0.0196 - but I don't get it (so I'm doing something wrong)??.

I have now changed the value from n under "#Vorbereitende Befehle" and then
run:

#Lösen der Problemstellungen durch R=1000 (oder mehr) Durchlaeufe
R <- 10000                                      #R Wiederholungen
erg <- rep(0,R)                                 #Abspeichern ob Bedingung erfuellt oder nicht
n <- 1000
for(i in 1:R){
  x <- sample(c(rep(1,n),rep(-1,n)),size=2*n)
  if(min(cumsum(x))>=0){erg[i] <- 1}            #falls Bedingung erfüllt kommt 1 in Vektor
}
mean(erg)                                       #Prozentsatz (=Schaetzung fuer Wahrscheinlichkeit)

Is that correct in principle?

You're setting n=1000 here, for n=50 I do get values around 0.196 with your code (though they do vary between 0.005 and 0.04).

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.