什么是随机种子? [英] What is random seed about?
问题描述
例如下面的代码.它具有随机类别.但是,它总是在各处产生相同的输出.在这种情况下,种子是哪个项目?
For example the code below. It has a random class. However it always produce the same output everywhere . In this case which item is the seed?
来源:链接
import java.util.Random;
public class RandomTest {
public static void main(String[] s) {
Random rnd1 = new Random(42);
Random rnd2 = new Random(42);
System.out.println(rnd1.nextInt(100)+" - "+rnd2.nextInt(100));
System.out.println(rnd1.nextInt()+" - "+rnd2.nextInt());
System.out.println(rnd1.nextDouble()+" - "+rnd2.nextDouble());
System.out.println(rnd1.nextLong()+" - "+rnd2.nextLong());
}
}
推荐答案
42 is the seed, as the very same Javadoc says. So, what is a seed? A random number is seldom truly random - often it's a pseudo-random instead. This means it's generated from a function, which is said PRNG (pseudo random number genrator). Being generated from a function, in turn, means that the output is not random anymore, since it's predictable!
但是,根据您的需要,这种伪随机性可能就足够了-我说足够,因为生成随机位很昂贵,而我不是在谈论时间或记忆,但关于金钱(请参阅Wikipedia上的此链接).因此,例如,如果您需要一个随机值来在游戏中放置敌人,则可以使用伪随机数-但是如果您要构建与安全相关的软件,则需要使用真实的随机数,或者至少使用通过密码保护的PRNG .
However, depending on your needs, this pseudo-randomness may be enough - I said enough because generating random bit is expensive, and I'm not talking about time or memory, but about money (see this link on wikipedia). So, for example, if you need a random value to place enemies in your game, a pseudo-random number is ok - but if your are building security-related software, you want to use a true random number, or at least a cryptographically secure PRNG.
我们如何描述PRNG,就像Math.random()
中使用的那样?这是一个用 seed S初始化的函数,该函数返回值A的数组.请注意,对于每个整数S,仅定义一个且仅一个数组A.例如(值不是实际的):
How can we describe a PRNG, like the one used in Math.random()
? It's a function, initialized with a seed S that returns an array of values A. Note that, for each integer S, is defined one and only one array A. For example (values are not actual):
first call second call third call
seed: 14329 .18 .82 .5
seed: 3989 .7 .02 .93
因此,当您希望PRNG的结果可预测时,可以为PRNG注入一些已知值-例如,出于测试目的或确保每次在游戏中运行1级时,敌人始终位于同一位置(伪随机位置)-否则,您无需显式传递种子.
So you seed you PRNG with some known value when you want its result to be predictable - for example for testing purposes or to ensure that, each time you run level 1 in your game, the enemies are always placed in the same (pseudo) random places - otherwise you don't need to explicitely pass a seed.
这篇关于什么是随机种子?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!