Distribution of Random Numbers

前端 未结 5 862
孤独总比滥情好
孤独总比滥情好 2021-02-04 17:22

I have two options of code:

Option 1

int myFunc() {
  return new Random().nextInt();
}

Or:

Option 2

5条回答
  •  温柔的废话
    2021-02-04 17:35

    No.

    There are no guarantees on the properties of the distribution of numbers that will be produced by Option 1. As has been made clear in other answers, the implementation of the constructor for java.util.Random depends on the system time. Therefore, in order to make a guarantee on the properties of the distribution of numbers you get with Option 1, you would need to be able to make guarantees about the distribution of numbers produced by the calls your program makes to get the system time on any platform where the program will be running.

    With option 2, however, there are mathematical guarantees that can be made about the distribution of numbers that will be produced during one execution of the program. With a linear congruential generator (the pseudorandom number generation algorithm used by java.util.Random) some of the properties of randomness are not quite as good as with other algorithms, but the distribution is guaranteed to be relatively uniform.

    This does not necessarily mean that Option 1 cannot serve your purposes. It depends on what you are doing.

提交回复
热议问题