Re: How to Compile this code (multiple random walks)
- To: mathgroup at smc.vnet.net
- Subject: [mg118086] Re: How to Compile this code (multiple random walks)
- From: Peter Pein <petsie at dordos.net>
- Date: Tue, 12 Apr 2011 05:55:45 -0400 (EDT)
- References: <inuncc$2dl$1@smc.vnet.net>
Am 11.04.2011 13:06, schrieb mfific at gmail.com:
> Transpose[{Range[0, Length[#] - 1], #}]&@
> NestWhileList[(# + {If[Random[]> .5, 1, -1],
> If[Random[]> .5, 1, -1], If[Random[]> .5, 1, -1]}
> )&, {0, 0, 0}, -5< #[[1]]< 5&& -5< #[[2]]< 5&& -5< #[[3]]
> < 5& ]
Hi Mario,
you _can_ compile the part that will be given to Transpose but
NestWhileList seems to be efficient enough.
I tried your version and
count3helper=Compile[{},
NestWhileList[# + 2 RandomInteger[1, {3}] - 1 &,
{0, 0, 0},
-5 < #[[1]] < 5 && -5 < #[[2]] < 5 && -5 < #[[3]] < 5 &],
{{_NestWhileList, _Integer, 2}},
CompilationTarget -> "C",
Parallelization -> True, RuntimeAttributes -> {Listable}
];
count3[] := Transpose[{Range[0, Length[#] - 1], #} &@
count3helper[]
]
using ParallelTable some times 10^6 times each and got timings for your
version of ~25 seconds and ~32 seconds for the compiled version above.
Sorry,
Peter
P.S.: I used
RandomSeed[1];
{tim, hst} = AbsoluteTiming[Histogram[ParallelTable[Length[count3[]],
{10^6}], PlotLabel -> "time here"]];
hst /. "time here" -> ToString[NumberForm[tim, 4]]
for testing.
P.P.S.:
changing the test in NestWhileList to
-5 < Min[#] && Max[#] < 5 &
results in timings ~24.3s for your and 27.6s for the compiled version.