gpt4 book ai didi

java - java中随机数生成器详解

转载 作者:搜寻专家 更新时间:2023-11-01 04:02:11 25 4
gpt4 key购买 nike

阅读关于 Fisher-Yates 的维基百科页面,将最后一段打乱是:

Finally, it is to be noted that even with perfect random number generation, flaws can be introduced into an implementation by improper usage of the generator. For example, suppose a Java implementation creates a new generator for each call to the shuffler, without passing constructor arguments. The generator will then be default-seeded by the language's time-of-day (System.currentTimeMillis() in the case of Java). So if two callers call the shuffler within a time-span less than the granularity of the clock (one millisecond in the case of Java), the generators they create will be identical, and (for arrays of the same length) the same permutation will be generated. This is almost certain to happen if the shuffler is called many times in rapid succession, leading to an extremely non-uniform distribution in such cases; it can also apply to independent calls from different threads. A more robust Java implementation would use a single static instance of the generator defined outside the shuffler function.

除了这一段的最后一句,我什么都懂。作者说:

A more robust Java implementation would use a single static instance of the generator defined outside the shuffler function.?

最佳答案

这意味着你有一个像这样的静态函数:

class RandomUtil {

public static final Random rand = new Random();

}

然后您使用此随机数生成器 RandomUtil.rand.nextInt() 生成您所有的随机数。您只使用这一个实例,并确保不会出现维基中提到的问题。

关于java - java中随机数生成器详解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11323245/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com