5

I am attempting to model a physical process I'm observing in the lab with a random walk generator. I need to find a way to impose a condition such that when the random walk runs into a point in the field it terminates. Then I need a way to measure the distance of the walk. I would like to have 4 of these points evenly spaced from the center of the circular area I am working in. The code I am using for the random walk (from this answer by C.E.) is the following:

step[position_, region_] := 
Module[{randomStep}, 
randomStep = RandomChoice[{{-1, 0}, {1, 0}, {0, -1}, {0, 1}}];
If[Element[position + randomStep, region], position + randomStep, 
position]]

randomWalk[region_, n_] := NestList[step[#, region] &, {0, 0}, n]

visualizeWalk[region_, n_] := 
Graphics[{White, region, Black, Line[randomWalk[region, n]]}, 
Background -> Black]

visualizeWalk[Disk[{0, 0}, 30], 10000]

This code produces the random walk. I'm new to mathematica but I understand the basic principles enough to run these codes.

kglr
  • 394,356
  • 18
  • 477
  • 896
natedice
  • 73
  • 2
  • As a way to end a random walk based on a condition, I checked the "StoppingFunction" method for RandomFunction. But it seems to only apply to Markov processes. It is not documented in general: I only found its use in examples for Discrete and Continuous Markov processes. – tad Apr 08 '20 at 23:55

1 Answers1

4

One could use NestWhileList.

steps = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
radius = 30;
region = Disk[{0, 0}, radius];
sinks = {{-radius, 0}, {0, -radius}, {radius, 0}, {0, radius}};

step[position_, region_] := With[{randomStep = RandomChoice[steps]},
   If[Element[position + randomStep, region], position + randomStep, 
    position]
   ];
stoppingRandomWalk[region_, n_] := 
 NestWhileList[step[#, region] &, {0, 0}, Not@MemberQ[sinks, #] &, 1, 
  n]

visualizeWalk[region_, walk_, sinks_] := 
 Graphics[{White, region, Black, Line[walk], Red, PointSize[0.02], 
   Point[sinks]}, Background -> Black]

SeedRandom[123]
walk = stoppingRandomWalk[region, 100000];

With this seed one gets:

Length[walk]
(* 2090 *)
walk[[-1]]
(* {30, 0} *)

visualizeWalk[region, walk, sinks]

walk

b.gates.you.know.what
  • 20,103
  • 2
  • 43
  • 84
  • perfect! thats exactly what I wanted to do. now is there a way to run this process with a counter? 1000 iterations and then make a graph of the lengths of the walks. I've been looking at making bins for a given length. – natedice Apr 09 '20 at 14:33
  • 1
    Please have a go at it, maybe using Map or Table ? – b.gates.you.know.what Apr 09 '20 at 15:06
  • @natedice that sounds like a great idea! If you make an attempt and have trouble with it, you’re always welcomed to ask another question to see if anyone has any valid input! I will recommend you make some attempt on your side, such that those who would want to answer have a better idea of what you’re trying to achieve :D – CA Trevillian Apr 10 '20 at 03:51