How could I save and restore the status of random seed?

as per the following, how could I make sure the random seed remains unchanged before and after calling the function?

function f()
    rng0 = Random.default_rng()    # save the current seed

    ### section for deterministic randomized algorithm
    Random.seed!(123)
    xxxxxx
    xxxxxxx
    ###

    # ??? how could I restore the seed to rng0 ???
end

thanks.

Random.seed!(rng0.seed) is one option.

Perhaps cleaner would be to leave the global random number generator alone:

function f()
  rng = MersenneTwister(123);
  x = rand(rng)
  [...]
end
3 Likes

Also, if you want determinism in your rands to hold across Julia versions, you probably want to use something like StableRNGs.jl further suggesting that @hendri54’s suggestion is best here.

3 Likes

The .seed field of the global RNG will soon not exist anymore (in Julia 1.7). An alternative would be to copy the state:

julia> rand()
0.09028876420540066

julia> state = copy(Random.default_rng())
MersenneTwister(0xacbf17e36353b3a3a75764abc1e03e06, (0, 1002, 0, 2))

julia> rand()
0.5688115492566419

julia> copy!(Random.default_rng(), state)
MersenneTwister(0xacbf17e36353b3a3a75764abc1e03e06, (0, 1002, 0, 2))

julia> rand()
0.5688115492566419

This should also be quite faster than re-seeding.

2 Likes