I'm trying to do a little Monte-Carlo, and the code is working great, but slows down when I try to increase the number of iterations, any suggestions on how I can parallelize this? Every way I've tried actually takes longer to run than the non-parallelized version.
n = 500
errors = {};
time = 60 60; (*seconds*)
velocity = 3.352;(*meters per second, about 8 minute/mile*)
gpserror = 4;(*meters*)
angles = {};
rands = {};
diss = {};
cf2 = Compile[{{gpserrx, _Real}, {gpserry, _Real}, {gpserr2x, _Real}, \
{gpserr2y, _Real}, {velocity, _Real}},
Sqrt[(gpserrx - gpserr2x - velocity)^2 + (gpserry - gpserr2y)^2]];
For[i = 1, i <= n, i++, {
gpspos = {0, 0},
gpsdistance = 0,
angle = RandomReal[{0, \[Pi]}, time + 1],
rand =
RandomVariate[
NormalDistribution[0, gpserror/(Sqrt[2] InverseErf[19/20])],
time + 1],
rands =
Append[rands,
Table[rand[[k]]*{Cos[angle[[k]]], Sin[angle[[k]]]}, {k, time}]],
DistributeDefinitions[rand, angle, cf2],
gpsdistance =
Sum[cf2[rand[[j]]*Cos[angle[[j]]], rand[[j]]*Sin[angle[[j]]],
rand[[j + 1]]*Cos[angle[[j + 1]]],
rand[[j + 1]]*Sin[angle[[j + 1]]], velocity], {j, 1, time}],
diss = Append[diss, gpsdistance],
errors = Append[errors, gpsdistance - velocity time]
}]
ReapandSowrather thanAppend– evanb Dec 13 '23 at 08:36