使用随机库Java播种产生相同的结果

时间:2015-04-15 20:02:01

标签: java random

我生成随机整数的方法如下:

public static int randInt(int min, int max) {

    Random rand = new Random(System.currentTimeMillis());

    int randomNum = rand.nextInt((max - min) + 1) + min;

    return randomNum;
}

我用这个来为旅行商问题选择随机路线。

但由于一些奇怪的原因,它在约5秒后仍然找到相同的路线。

有一点变化,但几乎相同。知道为什么会这样吗?

我的猜测是,在几毫秒内,它不够精确。我应该下降到纳秒?

2 个答案:

答案 0 :(得分:1)

根据您每秒调用方法的频率,使用相同的种子初始化Random。如前所述,在方法之外实例化Random

一个用于演示问题的小片段

public static void main(String[] args) {
    System.out.println("random with same seed");
    for (int i = 0; i < 10; i++) {
        Random rand = new Random(System.currentTimeMillis());
        System.out.println(rand.nextInt(100));
    }

    System.out.println("random initialized once");
    Random rand = new Random(System.currentTimeMillis());
    for (int i = 0; i < 10; i++) {
        System.out.println(rand.nextInt(100));
    }
}

输出(您的输出将具有不同的值)

random with same seed
13
13
13
13
13
13
13
13
13
13
random initialized once
13
96
11
34
44
22
80
10
41
36

如果您使用相同的种子创建Random,它将生成相同的&#34;随机&#34;值和相同的连续顺序。如果您只初始化Random一次并且使用更少的随机种子,则会生成每个运行不同的连续值。

答案 1 :(得分:0)

重播:

public static void main(String[] args) {
    try {
        for (int i = 0; i < 5; i++)
            System.out.println(randInt(1, 100));
        Thread.sleep(5000);
        for (int i = 0; i < 5; i++)
            System.out.println(randInt(1, 100));
    } catch (InterruptedException ex) {
        System.out.println(ex.toString());
    }
}

public static int randInt(int min, int max) {
    Random rand = new Random(System.currentTimeMillis());
    int randomNum = rand.nextInt((max - min) + 1) + min;
    return randomNum;
}

结果:

enter image description here

作为类变量播种一次:

private static Random rand = new Random(System.currentTimeMillis());

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    try {
        for (int i = 0; i < 5; i++)
            System.out.println(randInt(1, 100));
        Thread.sleep(5000);
        for (int i = 0; i < 5; i++)
            System.out.println(randInt(1, 100));
    } catch (InterruptedException ex) {
        System.out.println(ex.toString());
    }
}

public static int randInt(int min, int max) {
    int randomNum = rand.nextInt((max - min) + 1) + min;
    return randomNum;
}

结果:

enter image description here