随机游走蒙特卡罗模拟

时间:2019-04-03 13:47:24

标签: java montecarlo random-walk

在为以下练习编写代码时遇到一些麻烦:

  

编写一个程序RandomWalkers.java,它接受两个整数命令行参数r和审判。在每个试验独立实验中,模拟一个随机游走,直到该随机游走者离起点的曼哈顿距离为r为止。打印平均步数。 An image preview here

程序的运行应如下所示:

~/Desktop/loops> java RandomWalkers 5 1000000
average number of steps = 14.98188

~/Desktop/loops> java RandomWalkers 5 1000000
average number of steps = 14.93918

~/Desktop/loops> java RandomWalkers 10 100000
average number of steps = 59.37386

~/Desktop/loops> java RandomWalkers 20 100000
average number of steps = 235.6288

~/Desktop/loops> java RandomWalkers 40 100000
average number of steps = 949.14712

~/Desktop/loops> java RandomWalkers 80 100000
average number of steps = 3775.7152

~/Desktop/loops> java RandomWalkers 160 100000
average number of steps = 15113.61108

我试图实现代码,但是我对代码逻辑持怀疑态度。

public class RandomWalkers {
public static void main(String [] args){
    int r = Integer.parseInt(args[0]);
    int trials = Integer.parseInt(args[1]);
    int x = 0;
    int y = 0;
    int distance = 0;
    int sumOfSteps = 0;
    double averageSteps = 0;
    int steps = 0;
    for(int i = 1 ; i <=trials ; i++){
        while(distance!=r){
            double random = Math.random();
            if(random > 0 && random < 0.25){
                x = x + 1;
                steps++;
            }
            if(random > 0.25 && random < 0.50){
                x = x - 1;
                steps++;
            }
            if(random > 0.50 && random < 0.75){
                y = y + 1;
                steps++;
            }
            if(random > 0.75 && random < 1){
                y = y - 1;
                steps++;

            }
            distance = Math.abs(x+y);
        }
        sumOfSteps = sumOfSteps + steps;
    }
    averageSteps = (double)(sumOfSteps / trials);
    System.out.println("average steps" + averageSteps);
}}

这是我的运行程序:

~/IdeaProjects/MonteCarloSimulation/src$ java RandomWalkers 5 1000000
average steps27.0
~/IdeaProjects/MonteCarloSimulation/src$ java RandomWalkers 5 1000000
average steps7.0

您可以看到平均步数与讲师给我的示例运行时模型有很大不同。除此之外,即使我将averageSteps变量设置为double,我的平均步长也始终是整数数据类型。

1 个答案:

答案 0 :(得分:0)

您的代码中存在一些问题。首先,您需要在每次试用后重置xydistancesteps变量。或者,甚至更好的是,在for循环的开头将它们定义并初始化为0,如下所示:

for(int i = 1 ; i <=trials ; i++){
        int x = 0;
        int y = 0;
        int distance = 0;
        int steps = 0;

        [...]
}

第二,您对Manhattan distance的实现不正确。该行应显示为

distance = Math.abs(x) + Math.abs(y);

关于小数点分隔符后缺少有效数字的问题,在代码中,您将其强制转换为整数运算结果的两倍,该运算返回整数。在执行实际的数学运算之前,您需要将整数之一转换为双 ,例如:

averageSteps = ((double)sumOfSteps / trials);