1
$\begingroup$

I am having trouble reproducing a random number from a compiled function with parallelization even with the random seed being set.

Specifically, running the following script should give the same value (the 3-dimensional vector) over time.

SeedRandom[1, Method -> "MersenneTwister"];
f = Compile[{{x, _Real}},
   RandomReal[x]
   ,
   CompilationTarget -> "C", RuntimeOptions -> "Speed", 
   RuntimeAttributes -> {Listable}, Parallelization -> True
   ];
args = Range[3];
f[args]

However, I first got {0.0607303, 0.00332708, 2.55753} first. Next time {0.468316, 0.0823131, 1.02696} after I quit the kernel in between.

I tried the same thing with SeedRandom[1, Method -> "ParallelMersenneTwister"];, SeedRandom[1, Method -> "ExtendedCA"];, etc., and other seed numbers, which did not help.

Removing Parallelization -> True would resolve the issue, but

(1) is there any way to get the random seed to work properly in compiled, parallelized functions; and

(2) could someone explain how parallelization works when it comes to random number generation?

$\endgroup$
3
  • $\begingroup$ Some related Q&A: (99786), (100833), (185772) $\endgroup$
    – Michael E2
    Commented May 23, 2023 at 2:46
  • $\begingroup$ Thank you for the comment. ParallelEvaluate[SeedRandom[157 + $KernelID]] or ParallelEvaluate[SeedRandom[157]] (with or without specific Method) as suggested there did not give reproducibility in my case even though they work in the examples from the previous posts that you refer to. $\endgroup$
    – Kohei
    Commented May 23, 2023 at 3:25
  • $\begingroup$ Sorry it didn't help. $\endgroup$
    – Michael E2
    Commented May 23, 2023 at 3:32

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.