使用种子的Java随机数 [英] Java random numbers using a seed

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

问题描述

这是我使用种子作为参数生成随机数的代码:

This is my code to generate random numbers using a seed as an argument:

double randomGenerator(long seed) {
    Random generator = new Random(seed);
    double num = generator.nextDouble() * (0.5);

    return num;
}

每次我给种子并尝试生成100个数字时,它们都是同样的。

如何解决这个问题?

Every time I give a seed and try to generate 100 numbers, they all are the same.
How can I fix this?

推荐答案

如果你给的是相同的种子,这是正常的。这是允许测试的一个重要特性。

If you're giving the same seed, that's normal. That's an important feature allowing tests.

选中此项以了解伪随机生成和种子:

Check this to understand pseudo random generation and seeds:

伪随机数生成器


伪随机数生成器(PRNG),也称为确定性
随机比特生成器DRBG,是一种生成序列
的数字的算法,该数字近似于随机数的属性。
序列不是真正随机的,因为它完全由
a确定的相对较小的初始值集合,称为PRNG的状态,
包括一个真正随机的种子。

如果你想拥有不同的序列(通常不调整或调试算法的情况),你应该调用零参数使用nanoTime的构造函数每次尝试获取不同的种子。这个随机实例当然应该保留在你的方法之外。

If you want to have different sequences (the usual case when not tuning or debugging the algorithm), you should call the zero argument constructor which uses the nanoTime to try to get a different seed every time. This Random instance should of course be kept outside of your method.

你的代码应该是这样的:

Your code should probably be like this:

private Random generator = new Random();
double randomGenerator() {
    return generator.nextDouble()*0.5;
}

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

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