In Julia set random seed and not generating same values if calling a function from different parts of program

I have a Julia program which runs some montecarlo simulations. To do this, I set a seed before calling the function that generates my random values. This function can be called from different parts of my program, and the problem is that I am not generating same random values if I call the function from different parts of my program.

My question is: In order to obtain the same reproducible results, do I have to call this function always from the same part of the program? Maybe this questions is more computer science related than language programming itself.

I thought of seeding inside the function with an increasing index but I still do not get same results.

Upvotes: 3

Views: 1740

Answers (1)

Antonello
Antonello

Reputation: 6423

it is easier to have randomness according to which are your needs if you pass to your function a RNG (random number generator) object as parameter.

For example:

using Random

function foo(a=3;rng=MersenneTwister(123))
  return rand(rng,a)
end

Now, you can call the function getting the same results at each function call:

foo() # the same result on any call

However, this is rarely what you want. More often you want to guarantee the replicability of your overall experiment. In this case, set an RNG at the beginning of your script and call the function with it. This will cause the output of the function to be different at each call, but the same between one run of the whole script and another run.

myGlobalProgramRNG = MersenneTwister() # at the beginning of your script...
foo(rng=myGlobalProgramRNG)

Two further notes: attention to multi-thread. If you want to guarantee replicability in case of multithreading, and in particular independently from the fact of your script running with 1, 2, 4,... threads, look for example how I dealt it in aML library using a generateParallelRngs() function.

The second notice is that even if you create your own RNG at the beginning of your script, or seed the default random seed, different Julia versions may (and indeed they do) change the RNG stream, so the replicability is guaranteed only within the same Julia version. To overcome this problem you can use a package like StableRNG.jl that guarantee the stability of the RNG stream (at the cost of losing a bit of performance)...

Upvotes: 3

Related Questions