I want to create a random walk using Module. The walk start at {0, 0}. At every step, x moves by a random integer in the range $[-a, a]$ and y by $[-b,b]$.
- 107,779
- 16
- 103
- 257
- 43
- 4
-
You just have to search the docs. In particular, see here under Aplications, and here. – Jens Mar 22 '15 at 00:53
-
possible duplicate of 2D random walk within a bounded area – C. E. Mar 22 '15 at 08:12
2 Answers
You can also use RandomVariate with DiscreteUniformDistribution:
rW[a_, b_, n_] := Accumulate[Prepend[
RandomVariate[DiscreteUniformDistribution[{{-a, a}, {-b, b}}], n]], {0,0}]
dt = rW[10, 20, 100];
Graphics[{PointSize[Large], Red, Point@#, Thick, Blue, Line@#} &@dt,
Frame -> True, Axes->True, AspectRatio -> 1/GoldenRatio]

We get the same picture with:
ListPlot[{dt, dt}, Joined -> {False, True},
BaseStyle -> {Thick, PointSize[Large]}, PlotStyle -> {Red, Blue},
Frame -> True]
- 394,356
- 18
- 477
- 896
a = 3;
b = 5;
randomWalk = NestList[# + {RandomInteger[{-a, a}], RandomInteger[{-b, b}]} &, {0, 0}, 100]
(*
{{0, 0}, {2, 2}, {1, -3}, {-2, 2}, {1, 4}, {1, 3}, {1, 2}, {4, 0}, {4,
0}, {3, -4}, {4, -1}, {2, -5}, {0, 0}, {0,
0}, {2, -3}, {3, -6}, {2, -11}, {4, -10}, {4, -5}, {7, -3}, {9, \
-3}, {6, -8}, {9, -12}, {7, -16}, {5, -11}, {6, -16}, {4, -11}, {3, \
-15}, {4, -13}, {5, -12}, {5, -14}, {3, -16}, {6, -20}, {5, -16}, {3, \
-12}, {0, -13}, {3, -8}, {2, -7}, {1, -9}, {2, -9}, {2, -7}, {2, -4}, \
{4, -5}, {3, -7}, {4, -12}, {4, -15}, {1, -17}, {-2, -21}, {-4, -24}, \
{-3, -21}, {0, -26}, {1, -22}, {1, -20}, {-2, -15}, {0, -17}, {2, \
-12}, {3, -8}, {6, -13}, {6, -18}, {5, -23}, {5, -22}, {5, -21}, {8, \
-24}, {11, -27}, {13, -22}, {13, -17}, {15, -16}, {12, -14}, {10, \
-18}, {8, -14}, {5, -19}, {3, -21}, {0, -26}, {2, -30}, {3, -29}, {2, \
-33}, {-1, -37}, {2, -33}, {4, -38}, {4, -39}, {4, -42}, {1, -40}, \
{-1, -44}, {0, -48}, {0, -43}, {-1, -41}, {-4, -39}, {-6, -38}, {-3, \
-38}, {-1, -41}, {-1, -36}, {0, -33}, {1, -37}, {0, -42}, {-3, -39}, \
{-5, -36}, {-3, -31}, {-2, -27}, {-1, -22}, {-4, -18}, {-2, -20}}
*)
Graphics[Line@randomWalk]

- 41,180
- 3
- 34
- 96
-
-
-
Accumulate[RandomVariate[DiscreteUniformDistribution[{{-a, +a}, {-b, +b}}], n]]– 2012rcampion Mar 22 '15 at 01:20 -
@2012rcampion Doesn't include $(0,0)$ as requested, but that's easily fixed. – David G. Stork Mar 22 '15 at 01:32
-
Accumulate[_]~Prepend~{0,0}. Of course none of these solutions useModuleas requested – 2012rcampion Mar 22 '15 at 01:44 -
Just realized that that's actually already kguler's answer... oops. – 2012rcampion Mar 22 '15 at 01:46