java - Simple 2D Random walk -


i'm having problem average distance in exercise. should close sqrt of n steps, it's lower. can me find out mistake?

2d random walk. 2 dimensional random walk simulates behavior of particle moving in grid of points. @ each step, random walker moves north, south, east, or west probability 1/4, independently of previous moves. determine how far away (on average) random walker starting point after n steps. (theoretical answer: on order of sqrt(n).)

public class randomwalk{     public static void main(string[] args){      int n = integer.parseint(args[0]);      double nextstep = 0;     double averagedistance = 0;     int count = 1000;      (int j = 0; j < count; j++){         int movewest = 0;         int moveeast = 0;         int movesouth = 0;         int movenorth = 0;         double distance = 0;          (int = 0; < n; i++){         nextstep = math.random()*4;         if (nextstep <= 1) ++movewest;           else if (nextstep <= 2) ++moveeast;             else if (nextstep <= 3) ++movesouth;               else if (nextstep <= 4)++movenorth;                }          moveeast = moveeast - movewest;         movenorth = movenorth - movesouth;         distance = math.sqrt((moveeast * moveeast) + (movenorth * movenorth));         averagedistance += distance;           system.out.println("walker " + distance + "\t steps away of starting point");         //system.out.println("sqrt of n " + math.sqrt(n));      }     system.out.println("average distance " + averagedistance/count + " steps away of starting point");     } } 

i ran few tests on code aforementioned change of ranges <0,1),<1,2),<2,3), <3,4) making them even.

and that:

if (nextstep < 1) ++movewest;           else if (nextstep < 2) ++moveeast;             else if (nextstep < 3) ++movesouth;               else if (nextstep < 4)++movenorth; 

notice <= becoming <.

100000 trials of 100 steps each gave resutls:

average distance 8.873435509749317 steps away of starting point w=2498906 e=2501447 n=2500022 s=2499625 

, w,e,n,s summed steps given direction during trials. fine.

running such test case couple of times reveals there no preferable direction. might use other methods random numbers, testing generators, not case. code looks ok point of view.

sentence problem statement gives clue:theoretical answer: on order of sqrt(n).


Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -