有没有办法获得随机数发生器的状态?

时间:2017-04-04 02:56:01

标签: random julia

假设我使用srand(123)播种123,并运行rand() X次。之后,我希望能够重新启动Julia并为一个数字(或状态)播种,这样当我再次运行rand()时,如果我有种子123并运行rand(),我将获得生成的数字X + 1次。有什么方法可以做到这一点,或者我真的必须运行rand() X次以获得我想要的状态?

1 个答案:

答案 0 :(得分:5)

如果Retrieve RNG seed in julia中提供的自定义随机数生成器的解决方案对您不可行,我能想到的最好的方法是复制全局随机数生成器的整个结构:

function reset_global_rng(rng_state)
    Base.Random.GLOBAL_RNG.seed = rng_state.seed
    Base.Random.GLOBAL_RNG.state = rng_state.state
    Base.Random.GLOBAL_RNG.vals = rng_state.vals
    Base.Random.GLOBAL_RNG.idx = rng_state.idx
end

rs = deepcopy(Base.Random.GLOBAL_RNG)
println(rand(5))
# [0.301558,0.602108,0.220952,0.0338732,0.553414]
reset_global_rng(rs)
println(rand(5))
# [0.301558,0.602108,0.220952,0.0338732,0.553414]

虽然我不能100%确定它是如何与random.jl中的dsfmt_gv_srand()进行交互的。