Stuart
Stuart

Reputation: 1492

Scope of Random Seed setting

I want to make a function that will always return the same numbers if I input a parameter asking for a deterministic response and will give a requested number of pseudorandom numbers otherwise. Unfortunately the only way I can figure out how to do it resets the global random seed which is not desirable.

Is there a way I can set the random number seed for one draw of pseudorandom numbers without affecting the global seed or the existing progression along that seed's pseudorandom number sequence?

Example Case

using Random
function get_random(n::Int, deterministic::Bool)
    if deterministic
        Random.seed!(1234)
        return rand(n)
    else
        return rand(n)
    end
end

Random.seed!(4321)
# This and the next get_random(5,false) should give the same response 
# if the Random.seed!(1234) were confined to the function scope.
get_random(5,false)
Random.seed!(4321)
get_random(5,true)
get_random(5,false)

Upvotes: 1

Views: 396

Answers (1)

Bogumił Kamiński
Bogumił Kamiński

Reputation: 69949

The simplest solution is to use newly allocated RNG like this:

using Random

function get_random(n::Int, deterministic::Bool)
    if deterministic
        m = MersenneTwister(1234)
        return rand(m, n)
    else
        return rand(n)
    end
end

In general I usually tend not to use global RNG in simulations at all as it gives me a better control of the process.

Upvotes: 4

Related Questions