Integer random number: comparison of two strategies

If you need an integer ransom number, here are two strategies. First get it from uniform distribution and take the integer part, second generate all integer possible values and take one randomly. The first solution is two times faster.


As seen in the last example, the manipulation of a vector of 50000 elements is not efficient at all.
However, if you know how many random numbers you will need, it is better to estimate first a long vector of random numbers and after get one per one.




1/ Using integer of uniform random number one by one: 1.994

> system.time(
+   for (i in 1:1000000)
+     a <- floor(runif(n = 1, min=1, max=50001))
+ )
utilisateur     système      écoulé 
      1.853       0.116       1.994

2/ Long vector of integer of uniform random number: 0.196

> system.time({+   ru <- floor(runif(n = 1000000, min=1, max=50001))
+   for (i in 1:1000000)
+     a <- ru[i]
+ }
+ )
utilisateur     système      écoulé 
      0.187       0.007       0.196 

3/ Take one random value from a long vector generated once: 4.529

> system.time(
+   {
+   serie <- 1:50000
+   for (i in 1:1000000)
+     a <- sample(x = serie, 1)
+   }
+ )
utilisateur     système      écoulé 
      4.427       0.041       4.529

4/ Generate long vector and randomize it: 0.147
The Winner !

> system.time({
+   ru <- sample(1:50000, 1000000, replace = TRUE)
+   for (i in 1:1000000)
+     a <- ru[i]
+ }
+ )
utilisateur     système      écoulé 
      0.139       0.008       0.147 

5/ Take one randomize value from a long vector generated many times: 143.988

> system.time(
+   {
+     for (i in 1:1000000)
+       a <- sample(x = 1:50000, 1)
+   }
+ )
utilisateur     système      écoulé 
     80.750      59.865     143.988 

Commentaires

Posts les plus consultés de ce blog

Standard error from Hessian Matrix... what can be done when problem occurs

stepAIC from package MASS with AICc

Install treemix in ubuntu 20.04