我在练习中遇到平均距离问题.它应该接近N步的sqrt,但它更低.你能帮我找出我的错误吗?
2D随机游走.
二维随机游走模拟在点网格中移动的粒子的行为.
在每一步,随机游走者以1/4的概率向北,向南,向东或向西移动,
独立于以前的动作.确定随机游走者距离N步之后的起点有多远(平均).
(理论答案: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");
}
}