vendredi 26 juin 2015

Inconsistent results for f(g(x)) together or split up

During a recent investigation into setting random seeds within functions, I came across an odd situation. Consider functions f and g, each of which sets the random seed and then performs a simple randomized operation:

g <- function(size) { set.seed(1) ; runif(size) }
f <- function(x) { set.seed(2) ; x*runif(length(x)) }

Because each function sets the random seed, I would expect each function to always have the same return value given the same input. This would mean f(g(2)) should return the same thing as x <- g(2) ; f(x). To my surprise this is not the case:

f(g(2))
# [1] 0.1520975 0.3379658

x <- g(2)
f(x)
# [1] 0.04908784 0.26137017

What is going on here?




Aucun commentaire:

Enregistrer un commentaire