Java 随机种子
我需要测试一个 Java 程序 20 次,并且需要设置随机种子以便可以重复测试。如果我将初始种子设置为 0,然后在每次运行时递增 1(即 1、2、3 等),即使种子相距不远,此方法是否仍能确保完全随机性?
谢谢
I need to test out a Java program 20 times and need to set the random seed so that the tests can be repeated. If I were to set the initial seed as 0 and then increment by 1 at each run (i.e. 1,2,3 etc), would this method still ensure complete randomness, even though the seeds are not far apart?
Thank you
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
对于标准 PRNG(如其中包含的种子),任何种子都将提供与任何其他种子相同级别的随机性与Java。因此,使用递增种子进行测试是可以的。
不过,您可能需要考虑使用更好的随机数生成器。如果将值呈现为图像,Java 中包含的模式会产生明显的重复模式(我无法立即找到参考,但我记得它很明显)。我推荐梅森旋转器(有 Java 版本)作为一种快速且周期很长的替代方案,因此您不会轻易看到模式。
Any seed will provide the same level of randomness as any other seed for a standard PRNG like the one included with Java. So it's fine to use an incrementing seed for tests.
You might want to consider using a better random number generator though. The one included with Java yields noticeable repeating patterns if you render the values as an image (I can't find a reference offhand, but I recall it being apparent). I'd recommend the Mersenne Twister (there are Java versions) as an alternative that's fast and has a very long period so you won't easily see patterns.
如果您使用种子 0,则随机数序列将从该点开始重复。如果您想要不同的序列,您只需要使用不同的随机种子。即您应该能够在每次测试时设置一次种子。
If you use a seed of 0 the sequence of random numbers will be repeatable from that point. You would only need to use a different random seed if you wanted a different sequence. i.e. you should be able to set the seed once per test.
为什么不直接使用当前时间作为种子呢?即,
System.currentTimeMillis()
?Why not just use the current time as the seed? ie,
System.currentTimeMillis()
?您需要一个数字还是一个字符串?我使用
UUID。当我需要字符串时,randomUUID().toString()
可以为我的测试获取 UUID,但如果您需要数字,则可以使用System.nanoTime()
。Do you need a number or a string? I use
UUID.randomUUID().toString()
to get a UUID for my tests when I need strings, but if you need a number then you can useSystem.nanoTime()
.