最佳Java随机种子 [英] optimal Java Random seed

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

问题描述

关于提供longjava.util.Random的种子,如果我实例化对象一次,看来如果我只是花时间作为种子,这对于程序的生命是令人满意的,这对于我目的意味着对nextDouble()的一系列调用的结果看起来是随机的.

In regard to providing the long to seed java.util.Random, if I instantiate the object once, it seems that if I just take the time as a seed that will be satisfactory for the life of the program, which for my purpose means that the result of a series of calls to nextDouble() looks random.

假设出于代码简化的原因,我实例化Random,将其使用多次,然后重新实例化并重复.如果以相似的方式提供种子,则种子将是相似的并且会增加,因为它是基于时间的.如果是自1970年1月1日以来的秒数,则与该值相比,增量将很小.(此问题在2011年提出.)

Suppose for reasons of code simplicity, I instantiate Random, use it several times, then re-instantiate, and repeat. If the seed is provided similarly, the seeds will be similar and increasing because it is based on the time. The increases will be small compared to the value if it is the number of seconds since January 1, 1970. ( This question was asked in the year 2011.)

如果我链接了nextDouble()的输出,并使用非随机的基于时间的种子对Random进行了重新实例化,则会导致微妙的模式出现在nextDouble()的输出复合链中.解决这个问题的另一种方法是:我是否需要从long集中统一提取一个种子.

If I chain the output of nextDouble() does the re-instantiation of Random with a non-random time-based seed cause a subtle pattern to appear in the composite chain of output from nextDouble(). Another way to phrase this question is: do I need a seed drawn uniformly from the set of long.

推荐答案

您可能会遇到这样的情况,即确实会为他们分配相同的种子,尤其是如果它们是在同一毫秒内创建的.有些机器的分辨率低至15毫秒或更高,因此这成为一个更大的问题.

You probably are likely to run into a situation like this where indeed they will get assigned the same seed, particuarly if they're created in the same millisecond. Some machines ahve a resolution as low as 15 milliseconds or more, so it becomes an even bigger problem.

解决这个问题的一种方法是使用Math.random().它使用系统范围内的随机实例,该实例只有在首次使用时才会实例化.我不相信您可以访问基础实例,因此无法使用它获取nextInt(),但是可以将Math.random()用于双精度,或者如果您确实想要自己的Random对象,则可以获取doubleMath.random()中,将其位转换为long,并使用该long作为新Random的种子.

One way toget around this is to use Math.random(). It uses a system wide random instance that only ever gets instantiated the first time it's used. I don't believe you have access to the underlying instance, so you can't use it to get nextInt() but you can use Math.random() for doubles, or if you really want your own Random object, get a double from Math.random(), convert its bits into a long and use that long as your seed for your new Random.

可以在此处.

// create new random with seed from system random
Random r = new Random(Double.doubleToLongBits(Math.random()));

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

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