Get RNG Seeds in Julia

In julia, seed for global RNG can be set using

srand(SEED) 

How can I get the initial or current state of a global RNG, for example. again at a later point?

The goal is to get the RNG state at any given time and recreate it in another session without knowing the seed or all the RNG calls that occurred at the same time.

For example, R allows access to the current seed through

 .Random.seed 

I was hoping that an equivalent way would exist in julia.

+6
source share
5 answers

Base.Random.RANDOM_SEED is your friend to get 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 is not documented, but the source is easy enough to read. I'm not sure how to get the current state of the RNG, but it could be in the dSFMT module

+4
source

Using a specialized MersenneTwister with an explicit variable (instead of the hidden global one provided by random default functions), you can be provided with the necessary functions:

 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 

deepcopy threw me off for a second. It would also be easier to access the global state of random generators, but it might require the ccall lib libSFMT library (see random.jl and dSFMT.jl in Base .

+2
source

You should get such a seed

 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 

To save the restoration of the full state of rng, you can do a simple thing and just save the entire Base.Random.GLOBAL_RNG object. An easy way would be to use JLD .

In my private package I manually save / read the rng state on HDF5, see here .

EDIT: This, of course, is a more explicit version of @IainDunning's answer

+1
source

The obvious solution is to keep the initial value before calling srand(seed) .

Alternatively, if you know the RNG used and are not cryptographically secure, you can calculate the values ​​from the pseudo-random numbers that it produces. For example, see Cracking a linear congruent generator.

0
source

For better control when using a random generator in functions and in general,

 RND = srand(0) function coolfun() println(RND.idx) output = srand(RND, 100) ... end 
0
source

Source: https://habr.com/ru/post/976865/


All Articles