Random julia v 1.7

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?!

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

Because I have old results that need to be reproducible.

1 Like

https://docs.julialang.org/en/v1/stdlib/Random/#Reproducibility

5 Likes

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 enable switching the default RNG (fix #23199) by rfourquet · Pull Request #23205 · JuliaLang/julia · GitHub.

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

See also:

1 Like

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