In the following Mathematica compiled program, 3 persons take turns in a fair Russian Roulette Game with 1 bullet in the 6th chamber and we find the probabilities of each person being killed after 1,000,000 repetitions of the experiment,
The program:
p = 3; n = 1000000.; arg = Table[0, n]; Roulette =
Compile[{i}, Module[{c = 1}, While[RandomInteger[{1, 6}]
!= 6, c++]; m = Mod[c, p]; If[m != 0, m, p]],
RuntimeAttributes -> {Listable}, Parallelization -> True,
RuntimeOptions -> "Speed"];
Counts[Roulette[arg]]/n // AbsoluteTiming
with Parallelization -> True, gives nonsense whereas without:
p = 3; n = 1000000.; arg = Table[0, n]; Roulette =
Compile[{i}, Module[{c = 1}, While[RandomInteger[{1, 6}]
!= 6, c++]; m = Mod[c, p]; If[m != 0, m, p]],
RuntimeAttributes -> {Listable},
RuntimeOptions -> "Speed"];
Counts[Roulette[arg]]/n // AbsoluteTiming
gives correct answer.
By including local variable m in the module as in:
p = 3; n = 1000000.; arg = Table[0, n]; Roulette =
Compile[{i}, Module[{m = 1,c = 1}, While[RandomInteger[{1, 6}]
!= 6, c++]; m = Mod[c, p]; If[m != 0, m, p]],
RuntimeAttributes -> {Listable}, Parallelization -> True,
RuntimeOptions -> "Speed"];
Counts[Roulette[arg]]/n // AbsoluteTiming
we take the correct answer this time, but parallelization still fails.
m
and using it in the result, so that could be a problem. $\endgroup$Mod[c,p,1]
from theModule
-- it's faster that way. $\endgroup$