如何获取rand()(C++)的源代码?

BBe*_*dit 11 c++ random

我是编程新手.

我想知道rand()究竟是什么.

仅搜索会生成有关其用法的示例.但没有人解释函数如何生成随机数的每一步.他们将rand()视为黑盒子.

我想知道rand()正在做什么; 每一步.

是否有资源可以让我看到rand()的确切含义? 这是所有开源的东西不是吗?如果没有消息来源,我会解决这个问题.

我知道它会返回一个随机数,但它是如何生成该数字的?我想看看每一步.

谢谢.

Car*_*rum 17

这是当前的glibc实现:

/* Return a random integer between 0 and RAND_MAX.  */
int
rand (void)
{
  return (int) __random ();
}
Run Code Online (Sandbox Code Playgroud)

这没什么帮助,但__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;
}
Run Code Online (Sandbox Code Playgroud)


seh*_*ehe 13

这是10秒的谷歌搜索:

...

我本来会列出实际搜索,但看到这显然是一个骗局,我只会投票作为欺骗

  • 好的。我对编程很陌生(约 3 天!)所以我不知道要搜索什么。我在这里找到了我需要研究的实现:http://bioen.okstate.edu/Home/prashm%20-%20keep/prashant/VS.NET%20setup%20files/PROGRAM%20FILES/MICROSOFT%20VISUAL%20STUDIO% 20.NET/VC7/CRT/SRC/RAND.C (2认同)
  • 谢谢你,现在是2秒:) (2认同)