I wrote the following code


simulateRandomWalk[steps_Integer, prob_] :=
  Module[{accumulatedSteps, plotRange},

   accumulatedSteps = 
      RandomChoice[{N[1 - prob], N[prob]} -> {-1, 1}, steps]], 0];
   plotRange = {{0, steps}, {Min[accumulatedSteps] - 1, 
      Max[accumulatedSteps] + 1}};

    ListLinePlot[{Range[0, n], Take[accumulatedSteps, n + 1]} // 
     PlotRange -> plotRange], {n, Range[0, steps], 
     AnimationRepetitions -> 1}

simulateRandomWalk[100, 0.5]

to simulate a random walk with $n$ steps and a probability $p$ of going up (and $1 - p$ for going down). However, it appears that ListLinePlot gives me some warnings/error that go away almost immediately, so I cannot see them well, let alone deal with them. Any ideas as to what I should do?

  • 1
    $\begingroup$ Just a guess: replace Module with DynamicModule. This doesn't answer how to diagnose errors, it's simply a suggestion based on experience. :-) $\endgroup$ – Mr.Wizard Mar 21 '15 at 10:39
  • $\begingroup$ @Mr.Wizard: Thanks; the lack of DynamicModule is indeed what was causing the problems! $\endgroup$ – d125q Mar 21 '15 at 11:45

Interesting! Add Pause[10] between your two lines, and you'll get some time to peruse the output. Equivalently, split it into two cells, and re-run the definition of simulateRandomWalk after you've got some valid output.

The output of Animate is "Dynamic". When a new definition of the module inside simulateRandomWalk is created, a new local variable called accumulatedSteps$5432 (or similar) is created, so the previous output from simulateRandomWalk is invalidated because the previous accumulatedSteps$4321 (or whatever the local variable happens to be called) gets deleted. The output of Animate then attempts to re-render but it has insufficient input so you get your error message. However, valid output gets re-created a few milliseconds later because the function simulateRandomWalk gets called next.

If you use DynamicModule instead of Module the issue goes away. I don't understand dynamic outputs well enough to explain the mechanics exactly.

  • $\begingroup$ DynamicModule is indeed what I needed! Thanks a lot for the clear explanation; I'll do some research on the subject myself (seeing as I'm relatively inexperienced with Mathematica). $\endgroup$ – d125q Mar 21 '15 at 11:46

If you use With instead and factor in plotRange directly, it also works flawlessly:

simulateRandomWalk[steps_Integer, prob_] := 
  With[{accumulatedSteps = 
      RandomChoice[{N[1 - prob], N[prob]} -> {-1, 1}, steps]], 0]},
    ListLinePlot[{Range[0, n], Take[accumulatedSteps, n + 1]}
      PlotRange -> {{0, steps},
      {Min[accumulatedSteps] - 1, 
       Max[accumulatedSteps] + 1}}],
    {n, Range[0, steps]}, AnimationRepetitions -> 1]];

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.