我知道如何实现它.但是,我想了解rand在内部是如何表现的,为什么有必要初始化rand函数的'seed'值.
换句话说 - rand函数如何使用种子值生成随机数?
确切的实现细节取决于实现者.但是GNU实现(glibc)实现了rand():http://sourceware.org/git/? p = glibc.git; a = blob; f = stdlib/random_r.c; hb = glibc-2.15#l361
评论很好地解释了它.
/* If we are using the trivial TYPE_0 R.N.G., just do the old linear
congruential bit. Otherwise, we do our fancy trinomial stuff,
which is the same in all the other cases due to all the global
variables that have been set up. The basic operation is to add
the number at the rear pointer into the one at the front
pointer. Then both pointers are advanced to the next location
cyclically in the table. The value returned is the sum generated,
reduced to 31 bits by throwing away the "least random" low bit.
Note: The code takes advantage of the fact that both the front and
rear pointers can't wrap on the same call by not testing the rear
pointer if the front one has wrapped. Returns a 31-bit random number. */
Run Code Online (Sandbox Code Playgroud)
关于你的问题为什么你总是需要一个种子价值:计算机科学中没有真正随机的数字.计算机(在计算理论中)是完全确定性的机器.他们不能以一种偶然的结果执行任何操作.
只有伪随机数生成器生成看起来随机的数字流,但它们仍然是确定性计算的结果.这就是您需要种子值的原因:每个种子都会产生不同的数字序列.当您使用相同的种子时,您将获得相同的伪随机数序列.
可以利用RNG在获得相同种子时始终返回相同序列的行为:例如,经典空间模拟Elite能够在一个整数中存储具有数百个行星的巨大宇宙.它是怎么做到的?整个宇宙是随机生成的.重新创建Universe所需的所有数据都是种子值,这总是导致生成完全相同的Universe.