Java random numbers not random?

后端 未结 4 463
感情败类
感情败类 2021-01-12 02:43

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

相关标签:
4条回答
  • 2021-01-12 03:20

    This:

       Random rand = new Random(100);
    

    You're giving the random number generator the same seed (100) each time you start the program. Give it something like the output from System.currentTimeMillis() and that should give you different numbers for each invocation.

    0 讨论(0)
  • 2021-01-12 03:29

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

    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).

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

    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());
    }
    
    0 讨论(0)
  • 2021-01-12 03:31

    Random number generators are really only pseudo-random. That is, they use deterministic means to generate sequences that appear random given certain statistical criteria.

    The Random(long seed) constuctor allows you to pass in a seed that determines the sequence of pseudo-random numbers.

    0 讨论(0)
  • 2021-01-12 03:38

    Hope this helps..

    Random r = new Random(System.currentTimeMillis());
    double[] rand = new double[500];
    for(int i=0;i<100;i++){
        rand[i] = r.nextDouble();
        //System.out.print(rand[i] + "\n");
    }
    //System.out.println();
    return rand[randomInt];
    
    0 讨论(0)
提交回复
热议问题