Python - randomint should be equal to C - rand

2024-04-25 02:20:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下C程序:

#include <stdio.h>
#include <time.h>
int main(int argc, char *argv[]){
    srand(time(NULL));
    printf("%d", rand());
}

这个Python脚本:

^{pr2}$

C程序中的RAND_MAX定义为2147483647。如果我在同一秒启动两个程序,它们应该打印相同的“随机”数字,但事实并非如此?在

有什么想法为什么?有没有实现不同的方法来获得伪随机数?种子肯定是一样的。在


Tags: 程序脚本includetimemainnullintstdio
2条回答

C的随机数发生器完全没有标准化。C11标准修订版在the footnote 295中指出

There are no guarantees as to the quality of the random sequence produced and some implementations are known to produce sequences with distressingly non-random low-order bits. Applications with particular requirements should use a generator that is known to be sufficient for their needs.

Python就是其中的一个应用程序:Python选择使用MT19937-32随机数生成器,也称为Mersenne Twister。C库不太可能使用MT19937-32来实现rand,并且使用相同的种子例程。在

他们唯一能保证的是你会得到一个伪随机数。你基本上无法保证它将如何工作。在

即使在两个不同的编译器上编译同一个C程序,也不能保证在调用rand()时得到完全相同的结果。在

你基本上想知道为什么掷两个不同的骰子,即使你掷的方式完全一样,结果却不一样。嗯,它们是不同的,结果也是如此。在

相关问题 更多 >