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.
source share