Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simulate coin toss for one week?

This is not homework. I am interested in setting up a simulation of a coin toss in R. I would like to run the simulation for a week. Is there a function in R that will allow me to start and stop the simulation over a time period such as a week? If all goes well, I may want to increase the length of the simulation period.

For example:

x <- rbinom(10, 1, 1/2)

So to clarify, instead of 10 in the code above, how do I keep the simulation going for a week (number of trials in a week versus set number of trials)? Thanks.

like image 949
Frank Zafka Avatar asked Dec 08 '22 23:12

Frank Zafka


1 Answers

Here is code that will continue to run for three seconds, then stop and print the totals.

x <- Sys.time()
duration <- 3 # number of seconds
heads <- 0
tails <- 0

while(Sys.time() <= x + duration){
  s <- sample(0:1, 1)
  if(s == 1) heads <- heads+1 else tails <- tails+1
  cat(sample(0:1, 1))
}
cat("heads: ", heads)
cat("tails: ", tails)

The results:

001100111000011010000010110111111001011110100110001101101010 ...
heads:  12713
tails:  12836

Note of warning:

At the speed of my machine, I bet that you get a floating point error long before the end of the week. In other words, you may get to the maximum value your machine allows you to store as an integer, double, float or whatever you are using, and then your code will crash.

So you may have to build in some error checking or rollover mechanism to protect you from this.


For an accelerated illustration of what will happen, try the following:

x <- 1e300
while(is.finite(x)){
  x <- x+x
  cat(x, "\n")
}

R deals with the floating point overload gracefully, and returns Inf.

So, whatever data you had in the simulation is now lost. It's not possible to analyse infinity to any sensible degree.

Keep this in mind when you design your simulation.

like image 82
Andrie Avatar answered Dec 30 '22 05:12

Andrie