dimanche 21 janvier 2018

How to exclude specific result of runif()?

When I want to generate a random number with runif() within a specific interval under exclusion of a particular value (e.g. 0.5) I can write this function ex.runif() who does the job, but it is hundreds of times slower than the normal runif(). Could anyone point me to a better solution?

ex.runif <- function(excl) {
  # ex.runif() excludes the specific value 'excl'
  q <- excl
  while (q == excl) {
    q <- runif(1, min = .25, max = .75)
    print(q)
  } }

set.seed(42)
ex.runif(0.5)
# [1] 0.707403

library(microbenchmark)
microbenchmark(ex.runif(.5), runif(1, min = .25, max = .75))
# Unit: microseconds
# expr         min      lq      mean   median       uq     max neval cld
# ex.runif 692.439 704.685 721.51135 715.2735 722.9275 962.373   100   b
# runif      2.041   2.551   3.49044   2.8070   3.3170  21.176   100  a 




Aucun commentaire:

Enregistrer un commentaire