monty
December 21, 2021, 2:50pm
1
How to change the default random generator?
this works:
rng=Random.MersenneTwister(1); rand(rng)
however, i prefer to use rand()
instead of rand(rng)
.
is it possible? this does not work
Random.seed!(Random.MersenneTwister(), 2); rand()
suggestions?!
jw3126
December 21, 2021, 2:58pm
2
My recommendation is to pass rng
explicitly. However if you really want to have it implicit you could do:
import Random
const RNG = Random.MersenneTwister(1)
rand(args...) = Random.rand(RNG, args...)
2 Likes
Just use seed!
without passing an RNG in, and it will seed the default RNG:
julia> Random.seed!(0)
TaskLocalRNG()
julia> rand()
0.4056994708920292
julia> Random.seed!(0)
TaskLocalRNG()
julia> rand()
0.4056994708920292
3 Likes
Also, why do you want to use MersenneTwister
? It’s pretty much strictly worse than the new one.
1 Like
monty
December 22, 2021, 3:38pm
5
Because I have old results that need to be reproducible.
1 Like
monty
December 22, 2021, 6:59pm
7
I still think might be nice to be able to change the default RNG.
If you really want, you can redefine some methods, but I don’t recommend it:
julia> rng = MersenneTwister(0); Random.default_rng() = rng; rand()
0.8236475079774124
julia> Random.seed!(0); rand()
0.8236475079774124
Other methods might need to be redefined, see the file “stdlib/Random/src/RNGs.jl” for details. Also this will need more work if you want to be thread-safe.
There was a discussion about allowing changing the default RNG, if you are interested, at https://github.com/JuliaLang/julia/pull/23205 .
This is unfortunately completely at odds with having the default RNG be fast, so it isn’t supported and likely won’t be. Consider: if the default RNG type is changeable, that would prevent inlining calls to it or specializing on the type in any way. So, if you need reproducibility of exact RNG streams, you’ll need to explicitly pass RNG arguments around.
5 Likes
monty
December 27, 2021, 5:25pm
11
Thank you very much! This is a very helpful discussion. I agree with your comments. I made changes in the code to explicitly pass RNG arguments.
1 Like