﻿ java – 简单的2D随机游走 - 代码日志

#### java – 简单的2D随机游走

2D随机游走.

(理论答案：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;

for (int j = 0; j < COUNT; j++){
int moveWest = 0;
int moveEast = 0;
int moveSouth = 0;
int moveNorth = 0;
double distance = 0;

for (int i = 0; i < 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 is " + distance + "\t steps away of from the starting point");
//System.out.println("Sqrt of N is " + Math.sqrt(N));

}
System.out.println("Average distance is " + averageDistance/COUNT + " steps away of from the starting point");
}
}
``````

``````if (nextStep < 1) ++moveWest;
else if (nextStep < 2) ++moveEast;
else if (nextStep < 3) ++moveSouth;
else if (nextStep < 4)++moveNorth;
``````

``````Average distance is 8.873435509749317 steps away of from the starting point
W=2498906
E=2501447
N=2500022
S=2499625
``````

,