3
$\begingroup$

I am trying to make a random walk simulation with Animate, but somehow it doesn't produce the animation I want.

SingleRandomWalk[k_] := Module[
  {pts = {{0, 0}}},
  Do[AppendTo[
    pts, {0, 
     pts[[i, 2]] + RandomVariate[NormalDistribution[0, 1/k]]}], {i, 1,
     k}];
  Print[pts];
  Animate[
   Graphics[{PointSize[0.03], Point[pts[[i]]]}, Axes -> True, 
    AspectRatio -> 2, PlotRange -> {{-1, 1}, {-2, 2}}], {i, 1, k+1}, 
   DefaultDuration -> 1]]
SingleRandomWalk[5]

Where is the problem?

$\endgroup$

2 Answers 2

4
$\begingroup$

Try

SingleRandomWalk[k_] := 
 Module[{pts = {{0, 0}}}, 
  Do[AppendTo[
    pts, {0, 
     pts[[i, 2]] + RandomVariate[NormalDistribution[0, 1/k]]}], {i, 1,
     k}];
  Print[pts];
  Animate[
   Graphics[{PointSize[0.03], Point[pts[[i]]]}, Axes -> True, 
    AspectRatio -> 2, PlotRange -> {{-1, 1}, {-2, 2}}], {i, 1, 
    Length@pts, 1}, DefaultDuration -> 1]]
SingleRandomWalk[5]

You need {i, 1, Length@pts, 1} and not {i, 1, Length@pts} otherwise Animate does not know it is discrete ! It will otherwise try to use continuous increments which does not work for Part

$\endgroup$
1
  • $\begingroup$ Thank you so much! $\endgroup$
    – Apocalypse
    Commented Mar 13, 2022 at 12:04
2
$\begingroup$

In your code, the step of the variable of the animation is wrong. In the document, it says

Animate[expr,{u,Subscript[u, min],Subscript[u, max]}]generates an animation of expr in which u varies continuously from Subscript[u, min] to Subscript[u, max].

which means that the variable of your code i in Animate[...pts[[i]], {i, 1, k+1}] is wrong as it can be decimal. You need to add a step such as {i, 1, k+1, 1}.

$\endgroup$
1
  • $\begingroup$ I get it know, thank you! $\endgroup$
    – Apocalypse
    Commented Mar 13, 2022 at 12:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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