我是新手程序员。
我想确切知道rand()函数的作用。
搜索只能得到关于它用法的例子,但没有一个解释函数如何生成随机数的每一步骤,它们把rand()函数视为黑盒子。
我想知道rand()在做什么,每一步都是怎样的。
有没有资源可以让我看到rand()的具体操作?这不都是开源的吗?如果没有源代码,我也可以接受反汇编结果。
我知道它返回一个随机数,但它是如何生成这个数字的呢?我想看到每一步。
谢谢。
这里是当前的glibc实现:
/* Return a random integer between 0 and RAND_MAX. */
int
rand (void)
{
return (int) __random ();
}
虽然这并没有太大帮助,但是__random
最终会调用__random_r
函数:
/* 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. */
int
__random_r (buf, result)
struct random_data *buf;
int32_t *result;
{
int32_t *state;
if (buf == NULL || result == NULL)
goto fail;
state = buf->state;
if (buf->rand_type == TYPE_0)
{
int32_t val = state[0];
val = ((state[0] * 1103515245) + 12345) & 0x7fffffff;
state[0] = val;
*result = val;
}
else
{
int32_t *fptr = buf->fptr;
int32_t *rptr = buf->rptr;
int32_t *end_ptr = buf->end_ptr;
int32_t val;
val = *fptr += *rptr;
/* Chucking least random bit. */
*result = (val >> 1) & 0x7fffffff;
++fptr;
if (fptr >= end_ptr)
{
fptr = state;
++rptr;
}
else
{
++rptr;
if (rptr >= end_ptr)
rptr = state;
}
buf->fptr = fptr;
buf->rptr = rptr;
}
return 0;
fail:
__set_errno (EINVAL);
return -1;
}
这只需要10秒钟的谷歌搜索:
...
我本来想列出实际的搜索结果,但由于这很明显是重复的,所以我会标记它为重复。
GNU libc rand
很难。从标题中复制的 rand() (C++)
源代码也给我带来了不错的结果。 - Bartek BanachewiczX_{n+1} = (a * X_n + c) modulo m
真正好的伪随机数生成器更加复杂,例如Mersenne Twister。
如果我错了,请纠正我,尽管this answer指向了实现的一部分,但我发现在stdlib
中使用的rand()
还有更多内容,这些内容来自于[glibc][2]
。从2.32版本中获取的here,stdlib
文件夹包含一个random.c
文件,其中解释了使用简单的线性同余算法。该文件夹还有rand.c
和rand_r.c
,可以显示更多源代码。在同一文件夹中包含的stdlib.h
将向您展示用于宏的值,例如RAND_MAX
。
rand()
也是如此。) - Hot Licks