# Programming a 2D random walk

I have these functions

Randomwalk1[n_] :=Accumulate[2*RandomInteger[{0, 1}, n] - 1];

Randomwalk2[n_] := NestList[# + 2*RandomInteger[{0, 1}] - 1 &, 0, n]


that are random walks in 1D and I have to modify them to get a random walk in 2D, the walker can move right, left, step back or move forward with same probability 1/4 .. I'm a beginner and really don't know how to do that..

Thanks

I was thinking about an other way to do that without using these functions but I don't know if it can work and don't know how to do that in mathematica, here is the idea

if RandomInteger[{1,2}]=1 the walker moves in x direction

and if RandomInteger[{1,2}]=2 the walker moves in y direction

Then we call 2*RandomInteger[{0, 1}] - 1 to randomly generate -1 or +1 and the walker makes this step in the direction that was first determined

• Have you seen RandomChoice[]? Oct 8, 2015 at 4:47
• We didn't see a lot ! But we have the right to use everything in mathematica Oct 8, 2015 at 5:07
• From the help data2d = RandomFunction[RandomWalkProcess[0.5], {0, 10^3}, 2]; Graphics[Line[Transpose@data2d["States"]], AspectRatio -> Automatic] Oct 8, 2015 at 5:30
• A shorter version for your one-dimensional problem using RandomChoice as suggested by @J.M.: randomwalk[n_] := Accumulate[RandomChoice[{-1, 1}, n]]. The extension to the 2D case that you are asking for would read: randomwalk2d[n_] := Accumulate[RandomChoice[{-1, 1}, {n, 2}]].
– user31159
Oct 8, 2015 at 5:37
• @blochwave Yes I agree, this would be an unfortunate wording though.
– user31159
Oct 8, 2015 at 15:01

I am also new. But I think the following works

randomwalk[n_] :=
NestList[move :=
RandomChoice[{{1, 0}, {-1, 0}, {0, 1}, {0, -1}}]; # + move &, {0,
0}, n]

• You can make your code a little simpler with: Randomwalk[n_] := NestList[# + RandomChoice[{{1, 0}, {-1, 0}, {0, 1}, {0, -1}}] &, {0, 0}, n].
– user31159
Oct 8, 2015 at 5:46

Try this:

    Manipulate[
list = Accumulate[RandomInteger[{-1, 1}, {stepsNumber, 3}]];
xmin = Min[(Transpose@list)[]];
xmax = Max[(Transpose@list)[]];
ymin = Min[(Transpose@list)[]];
ymax = Max[(Transpose@list)[]];
zmin = Min[(Transpose@list)[]];
zmax = Max[(Transpose@list)[]];

Animate[

Show[{
Graphics3D[{Blue, Line[Take[list, i]]}],
Arrow[{First[list], list[[i]]}]}]
}, PlotRange -> {{xmin, xmax}, {ymin, ymax}, {zmin, zmax}},
ImageSize -> {400, 400}],
{i, 2, Length[list], 1}, AnimationRepetitions -> 1,
AnimationRunning -> False], {{stepsNumber, 2

}, ControlType -> InputField, FieldSize -> 7},
SaveDefinitions -> False]


Put an integer number (say, 10000) into the input field and press the arrow button. That's what you should get: Have fun!