C语言 兰德实施

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4768180/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 07:34:35  来源:igfitidea点击:

Rand Implementation

cgccrandom

提问by nikhil

I would like to go through how rand() and srand() functions are implemented and would like to tweak the code to modify it to my requirements. Where can i find the source code of rand() and srand().

我想了解 rand() 和 srand() 函数是如何实现的,并想调整代码以根据我的要求进行修改。我在哪里可以找到 rand() 和 srand() 的源代码。

采纳答案by evandrix

It takes a seed as in input argument, usually like follows:-

它采用输入参数中的种子,通常如下所示:-

double result = srand(time(NULL));

and returns a random number that adheres to the probability and hence expected number of occurrences.

并返回一个符合概率和预期出现次数的随机数。

from CodeGuru forums:-

来自CodeGuru 论坛:-

void __cdecl srand (unsigned int seed)
{
    #ifdef _MT
        _getptd()->_holdrand = (unsigned long)seed;
    #else /* _MT */
        holdrand = (long)seed;
    #endif /* _MT */
}

int __cdecl rand (void)
{
   #ifdef _MT
    _ptiddata ptd = _getptd();
    return( ((ptd->_holdrand = ptd->_holdrand * 214013L + 2531011L) >> 16) &
    0x7fff );
   #else /* _MT */
    return(((holdrand = holdrand * 214013L + 2531011L) >> 16) & 0x7fff);
   #endif /* _MT */
}

Hope this helps.

希望这可以帮助。

回答by Matteo Italia

randand srandare usually implemented as a simple LCG, you can easily write your own (it's few lines of code) without looking for the sources of randand srand. Notice that, if you need random numbers for "serious" purposes (e.g. cryptography), there are much better RNGs than LCG.

randsrand通常被实现为一个简单的LCG,你可以很容易地编写自己的(代码它的几行),而不找的来源randsrand。请注意,如果您出于“严肃”目的(例如密码学)需要随机数,那么 RNG 比 LCG 好得多。

By the way, the C standard itself includes a sample implementation of randand srand:

顺便说一下,C 标准本身包括一个rand和的示例实现srand

static unsigned long int next = 1;

int rand(void) // RAND_MAX assumed to be 32767
{
    next = next * 1103515245 + 12345;
    return (unsigned int)(next/65536) % 32768;
}

void srand(unsigned int seed)
{
    next = seed;
}

回答by paxdiablo

The glibc one (used by gcc) is the simple formula:

glibc 之一(由 gcc 使用)是简单的公式:

x = 1103515245 * x + 12345

wrapping around at 232, as shown here. You can just set xas the seed then keep calling a function to evaluate that expression (and update the seed).

缠绕在2 32,如图所示在这里。您可以设置x为种子,然后继续调用函数来评估该表达式(并更新种子)。

But you should be aware the linear congruential generators like this are considered adequate but not ideal.

但是你应该知道像这样的线性同余生成器被认为是足够的,但并不理想。

While the only ideal random number generator would be perfectly random, the Mersenne Twisterprobably comes closer.

虽然唯一理想的随机数发生器是完全随机的,但Mersenne Twister可能更接近。