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
Created
April 15, 2024 12:34
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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