How should I understand the scope of Random.seed?

function testing()

    function gen_a()
        return rand()
    end

    function gen_b()
        Random.seed!(111)

        return rand()
    end

    return gen_a() + gen_b()
end

testing()

result : 0.8538390963198838

Everytime I get the same value. My understanding was that the Random.seed! should fix only the RNG inside gen_b(). How can I set it locally only inside gen_b() function?

Well they both use the same global one (thread-local) by default, so you’ll get the same value after the second invocation, because then gen_a() will always do the same second value in the rng seeded by b the run before.

You can create a separate random number generator for b instead and pass that to rand(), have a look at this page in the docs Random Numbers · The Julia Language

Looks something like this example on that page

julia> rng = MersenneTwister(1234);

julia> randexp(rng, Float32)
2.4835055f0
1 Like

Thank you very much

function testing()

    function gen_a()
        return rand()
    end

    function gen_b()
        a = MersenneTwister(1234);

        return rand(a)
    end

    return gen_a() + gen_b()
end


testing()

This works out as expected !

If you want fast RNG, use Xoshiro (also from the Random stdlib) instead of MersenneTwister. It’s also the type of the default RNG.

4 Likes