Simulate a coin toss in one week?

This is not homework. I am interested in creating a coin toss simulation in R. I would like to run a simulation within a week. Is there a function in R that will allow me to start and stop the simulation for a period of time such as a week? If all goes well, I can extend the duration of the simulation period.

For instance:

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

So, to clarify, instead of 10 in the code above, how to keep the simulation for a week (the number of samples per week compared to the established number of tests)? Thanks.

+4
source share
3 answers

Here is a code that will last 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) 

Results:

 001100111000011010000010110111111001011110100110001101101010 ... heads: 12713 tails: 12836 

Warning note:

At the speed of my machine, I'm sure you will get a long floating point error until the end of the week. In other words, you can get the maximum value that your machine allows you to store as an integer, double, float, or whatever you use, and then your code will work.

Therefore, you may have to create an error checking or rollover mechanism to protect you from this.


To quickly illustrate what will happen, try the following:

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

R correctly handles floating point overloads and returns Inf .

So, all the data that you had in the simulation is now lost. It is impossible to analyze infinity to any reasonable degree.

Keep this in mind when you design your simulation.

+11
source

While now in less than a week, a timestamp is added to x rbinmo(1,1,1/2)

 R> week_later <- strptime("2012-06-22 16:45:00", "%Y-%m-%d %H:%M:%S") R> x <- rbinom(1, 1, 1/2) // init x R> while(as.numeric(Sys.time()) < as.numeric(week_later)){ R> x <- append(x, rbinom(1, 1, 1/2)) R> } 
+3
source

You might be interested in the fairly new harvestr package from Andrew Redd. It splits the task into parts (the idea is that the parts can run in parallel). The part of the package that applies to your question is that it caches the results of the processed fragments, so if the task is overloaded and restarted, then the completed parts will not be restarted, but it will be raised by those that were not completed (parts that were partially confused, will start from the beginning of this part).

This may allow you to start and stop the simulation at your request.

0
source

All Articles