Skip to content

Instantly share code, notes, and snippets.

@PietrH
Created April 15, 2024 12:34
Show Gist options
  • Save PietrH/c26ac86715b727f8315397f7903f17e1 to your computer and use it in GitHub Desktop.
Save PietrH/c26ac86715b727f8315397f7903f17e1 to your computer and use it in GitHub Desktop.
Non repeatable results in R, even with seed set. Due to calls to random number generator by functions.
my_good_function <- function(seed = 789) {
  invisible(withr::with_seed(seed, rnorm(1)))
}
my_bad_function <- function() {
  invisible(rnorm(1))
}

# good pattern
set.seed(123)
good_first_rand <- rnorm(1) |> print()
#> [1] -0.5604756
my_good_function()
good_second_rand <- rnorm(1) |> print()
#> [1] -0.2301775

# bad pattern
set.seed(123)
bad_first_rand <- rnorm(1) |> print()
#> [1] -0.5604756
my_bad_function()
bad_second_rand <- rnorm(1) |> print()
#> [1] 1.558708

# A user would expect repeatable results when seed is set, so as
good_first_rand == bad_first_rand
#> [1] TRUE

# bad pattern is caused because my_bad_function() caused the second rand to be
# different as expected
good_second_rand == bad_second_rand
#> [1] FALSE
my_good_function <- function(seed = 789) {
invisible(withr::with_seed(seed, rnorm(1)))
}
my_bad_function <- function() {
invisible(rnorm(1))
}
# good pattern
set.seed(123)
good_first_rand <- rnorm(1) |> print()
#> [1] -0.5604756
my_good_function()
good_second_rand <- rnorm(1) |> print()
#> [1] -0.2301775
# bad pattern
set.seed(123)
bad_first_rand <- rnorm(1) |> print()
#> [1] -0.5604756
my_bad_function()
bad_second_rand <- rnorm(1) |> print()
#> [1] 1.558708
# A user would expect repeatable results when seed is set, so as
good_first_rand == bad_first_rand
#> [1] TRUE
# bad pattern is caused because my_bad_function() caused the second rand to be
# different as expected
good_second_rand == bad_second_rand
#> [1] FALSE
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment