In julia, the seed for the global RNG can be set with
srand(SEED)
How can I retrieve the seed or current state of the global RNG, e.g. again at a later point?
The goal is to get the state of the RNG at any given point in time, and recreate it in a different session, without knowing the initial seed or all calls to RNG that happened in the meanwhile.
For example, R allows access to the current seed through
.Random.seed
I was hoping that an equivalent way would exist in julia.
Base.Random.RANDOM_SEED
is your friend for getting the seed:
julia> srand(10)
julia> Base.Random.RANDOM_SEED
1-element Array{Uint32,1}:
0x0000000a
julia> srand(1)
julia> Base.Random.RANDOM_SEED
1-element Array{Uint32,1}:
0x00000001
julia> srand(0xF)
julia> Base.Random.RANDOM_SEED
1-element Array{Uint32,1}:
0x0000000f
This isn't documented, but the source is easy enough to read. I'm not sure how to get the current state of the RNG, but it might be in the dSFMT
module
You should get the seed like this
reinterpret(Int32, Base.Random.GLOBAL_RNG.seed)
Test:
julia> srand(123456789);
julia> reinterpret(Int32, Base.Random.GLOBAL_RNG.seed)
1-element Array{Int32,1}:
123456789
For saving an restoring the full rng state you can do the simple thing and just store the whole Base.Random.GLOBAL_RNG
object. An easy way would be using JLD package.
In my private package I do manually save/read the rng state to HDF5, see here.
EDIT: This of course a more explicit version of @IainDunning's answer
Using a specialized MersenneTwister with an explicit variable (instead of the hidden global one provided by the default random values functions), the functionality you require can be provided:
newmt = Base.Random.MersenneTwister(123)
randvec = [rand(newmt) for i=1:100]
# save state now
savestate = deepcopy(newmt.state)
randvec2 = [rand(newmt) for i=1:20]
# rewind state to old state
newmt.state = savestate
randvec3 = [rand(newmt) for i=1:20]
if randvec2==randvec3
println("works!")
end
The deepcopy
threw me off for a second there. Also, it would have been easier to access the global random generator state, but it might require ccall
ing libdSFMT library (see random.jl
and dSFMT.jl
in Base
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With