MathGroup Archive 2006

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: Faster Random Walk Simulation ?!?

  • To: mathgroup at smc.vnet.net
  • Subject: [mg66421] Re: Faster Random Walk Simulation ?!?
  • From: Paul Abbott <paul at physics.uwa.edu.au>
  • Date: Thu, 11 May 2006 05:36:30 -0400 (EDT)
  • Organization: The University of Western Australia
  • Sender: owner-wri-mathgroup at wolfram.com

In article <e39k1n$cmn$1 at smc.vnet.net>,
  "mfific at gmail.com" <mfific at gmail.com> wrote:

>  I am running a simulation with Mathematica 5 that includes random walk
>  described below. The argument boundaryA is upper and lower boundary for
>  a random walk. Parameter "value" is just a constant arbitrarily set to
>  0.5. The output of the table function is the 10000 random walks, and
>  their path to either +5 or -5 boundary value.
>  While everything works as expected, it takes considerable duration of
>  time. For example it takes 2.6 seconds to generate the table output, on
>  a relatively fast computer.
>
>  I would very appreciate if any significantly faster solution could be
>  suggested.
>
>  value = .5
>
>  RandomWalk[boundaryA_] := Block[{l = {{0, 0}}, x = 0,
>    i = 0 }, While[boundaryA > x > -boundaryA,
>         x += If[Random[] > value, 1, -1];
>        l = Append[l, {++i, x}]];
>      l]
>
>  Timing[Table[RandomWalk[5], {i, 1, 10000}];]
>
>  Out[420]=
>  {2.672 Second, Null}

There is no need to index the number of steps to reach the boundary (you
can obtain the number of steps from the length of the result).

The following compiled function, which takes two parameters (n ->
boundaryA and r -> value), is considerably faster:

   Clear[RandomWalk];

   RandomWalk = Compile[{{n, _Integer}, {r, _Real}},
     NestWhileList[Function[x, x + If[Random[] > r, 1, -1]], 0,
       Function[x, -n < x < n]]]

   Timing[Table[RandomWalk[5, 0.5], {i, 1, 10000}];]
   {0.384 Second, Null}

Cheers,
Paul

_______________________________________________________________________
Paul Abbott                                      Phone:  61 8 6488 2734
School of Physics, M013                            Fax: +61 8 6488 1014
The University of Western Australia         (CRICOS Provider No 00126G)
AUSTRALIA                               http://physics.uwa.edu.au/~paul


  • Prev by Date: Re: Evaluating integrals
  • Next by Date: Re: Geodesics with NDSolve
  • Previous by thread: Re: Faster Random Walk Simulation ?!?
  • Next by thread: Beginner--Help on using FindRoot to solve the system of equations