Java随机数不是随机的? [英] Java random numbers not random?

查看:371
本文介绍了Java随机数不是随机的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用Java解释随机数生成器给朋友,因为他每次运行程序时都会得到相同的数字。我创建了我自己的同一个更简单的版本,我也得到了他每次运行程序时获得的相同数字。

I was trying to explain the random number generator in Java to a friend when he kept getting the same numbers every time he ran the program. I created my own simpler version of the same thing and I too am getting the same exact numbers he was getting every time I run the program.

我做错了什么?

import java.util.*;

public class TestCode{
   public static void main(String[] args){
       int sum = 0;
       Random rand = new Random(100);
       for(int x = 0; x < 100; x++){
           int num = (rand.nextInt(100)) + 1;
           sum += num;
           System.out.println("Random number:" + num);
       }
       //value never changes with repeated program executions.
       System.out.println("Sum: " + sum); 
   }

}

最后五个数字100是:

The final five numbers out of the 100 are:

40
60
27
56
53


推荐答案

您已经为随机生成器播种了一个常量值 100 。这是确定性的,因此每次运行都会产生相同的值。

You have seeded the random generator with a constant value 100. It's deterministic, so that will generate the same values each run.

我不确定你为什么选择 100 ,但种子值与生成的值范围无关(由其他方式控制,例如调用 nextInt 您已经有)。

I'm not sure why you chose to seed it with 100, but the seed value has nothing to do with the range of values that are generated (that's controlled by other means, such as the call to nextInt that you already have).

要每次获取不同的值,请使用 Random 构造函数,不带参数,使用系统时间为随机生成器播种。

To get different values each time, use the Random constructor with no arguments, which uses the system time to seed the random generator.

从Javadoc引用无参数随机构造函数:

Quoting from the Javadoc for the parameterless Random constructor:

创建一个新的随机数生成器。此构造函数将随机数生成器的种子
设置为与此构造函数的任何其他调用非常可能不同的值

Creates a new random number generator. This constructor sets the seed of the random number generator to a value very likely to be distinct from any other invocation of this constructor.

在无参数随机构造函数中引用实际代码:

Quoting the actual code in the parameterless Random constructor:

public Random() {
    this(seedUniquifier() ^ System.nanoTime());
}

这篇关于Java随机数不是随机的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆