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

查看:27
本文介绍了使用种子的 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,是一种生成序列的算法近似于随机数特性的数.这序列不是真正随机的,因为它完全由一组相对较小的初始值,称为 PRNG 的状态,其中包括一个真正随机的种子.

A pseudorandom number generator (PRNG), also known as a deterministic random bit generator DRBG, is an algorithm for generating a sequence of numbers that approximates the properties of random numbers. The sequence is not truly random in that it is completely determined by a relatively small set of initial values, called the PRNG's state, which includes a truly random seed.

如果你想要不同的序列(不调整或调试算法时的常见情况),你应该调用零参数构造函数,它使用 nanoTime 每次尝试获取不同的种子.这个 Random 实例当然应该放在你的方法之外.

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天全站免登陆