gpt4 book ai didi

计算机时钟作为伪随机发生器

转载 作者:行者123 更新时间:2023-11-30 21:21:59 24 4
gpt4 key购买 nike

大多数现代计算机都表现出不确定性行为,这使得无法判断两次连续调用读取计算机时钟之间会发生多少个时钟周期。

以下代码是使用计算机时钟的一个字节的伪随机数生成器。

unsigned long occurrences = 0;
unsigned long total = 0;

while (true) {
if ((clock() & 0xFF) == 60) // testing ocurrences for a given number, 60 for instance
occurrences++;
total++;
printf("%f\n", (float)occurrences / (float)total ); // this should be approximately 1/256 = 0.00390625
}

除了像加密这样的严肃应用程序之外,它还可以用于游戏的移动平台。

我想知道这种实现的优点和缺点是什么。

最佳答案

您缺少使用 rand() 的正确方法,或者更具体地说,使用 srand()

您需要在程序运行期间精确调用srand()一次。不要在循环中调用srand()。不要在每次调用 rand() 之前调用 srand()。确保正确的 srand() 管理的最佳方法是在 main() 函数中调用一次,然后忘记它:只需使用 rand() 之后。

#include <stdlib.h> /* rand, srand */
#include <time.h> /* time */

int main(void) {
/* initialization */
srand(time(NULL));

/* input, possibly calling rand() */

/* process, possibly calling rand() */

/* output, possibly calling rand() */

/* termination */
return 0;
}

关于计算机时钟作为伪随机发生器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14117229/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com