Re: How to Compile this code (multiple random walks)
- To: mathgroup at smc.vnet.net
- Subject: [mg118110] Re: How to Compile this code (multiple random walks)
- From: Oliver Ruebenkoenig <ruebenko at wolfram.com>
- Date: Tue, 12 Apr 2011 06:00:07 -0400 (EDT)
On Mon, 11 Apr 2011, mfific at gmail.com wrote: > Hi All, > > I would appreciate help with Compile function. Below is the code that > I could not compiled. The output are the three random walk counters > with (-5, 5) bounds, along with a counter for a number of steps. The > compile does not work here, I assume because the output is a matrix > (it works if there is only one counter). But I need these three > counters running in parallel for later development. Any help would be > appreciated. > > thanks, > > Mario Fific > > 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, I am not quite sure if there is a deeper reason (which I don not see right now) why NestWhileList can not be compiled. What is also odd, is that all elements created are packed but the returned list is not Developer`PackedArrayQ@ NestWhileList[(res = (# + Sign[RandomReal[{-1/2, 1/2}, {3}]]); Print[res, "", Developer`PackedArrayQ[res]]; res) &, Developer`ToPackedArray[{0, 0, 0}], -5 < #[[1]] < 5 && -5 < #[[2]] < 5 && -5 < #[[3]] < 5 &] I will file this as a suggestion - but as mentioned above, maybe there is something I do not get. What follows not is a compiled version that does something quite similar - the difference being in Sign[RandomReal[{-1/2, 1/2}, {3}]] which may behave differently because it can return 0, your version (If[..]) can not, but you could change that. cf = Compile[{}, Module[{start, n}, start = {{0, 0, 0}}; n = Length[start]; While[ -5 < start[[-1, 1]] < 5 && -5 < start[[-1, 2]] < 5 && -5 < start[[-1, 3]] < 5, start = Join[start, {start[[-1]] + Sign[RandomReal[{-1/2, 1/2}, {3}]]}] ]; start ]] cf[] A another improvement could be to not use Transpose[{Range[0, Length[#] - 1], #}] &@ This will unpack the the Developer`PackedArrayQ@cf[] You could either add the step, say, as the last entry in each of the returned lists, or keep it in a separate vector. Hope this helps, Oliver