为什么stdlib中的rand不遵循大数定律
Why does rand from stdlib not follow law of large numbers?
在下面的代码中,我预计一个骰子的角色数次平均结果正好是3.5,高于3.5的百分比有时是5%,其他时候(当然有不同的种子)是95。但是,即使你达到6040M thows,你也永远不会超过50%,低于3.5?显然rand()中有一点偏见。。。
我知道"真正的随机"并不存在,但它真的这么明显吗?
典型输出为:
平均值:3.50003计数器:3427000000以上百分比:83.2554计数器以上百分比:50.0011
平均值:3.49999计数器:1093000000以上百分比:92.6983计数器以上百分比:50.0003
#include <stdio.h> /* printf, scanf, puts, NULL */
#include <stdlib.h> /* srand, rand */
#include <time.h> /* time */
#include <unistd.h>
#include <iostream>
using namespace std;
int main ()
{
long long int this_nr;
long long int counter = 0;
long long int above_counter = 0;
long long int below_counter = 0;
long long int above_counter_this = 0;
long long int below_counter_this = 0;
long long int interval_counter = 0;
double avg = 0.0;
srand (time(NULL));
srand (time(NULL));
srand (time(NULL));
cout.precision(6);
while(1) {
this_nr = rand() % 6 + 1; // 0,1,2,3,4,5 or 6
avg = ((double) this_nr + ((double)counter * (double) avg))
/ ((double) counter+1.0);
if (this_nr <= 3) below_counter_this++;
if (this_nr >= 4) above_counter_this++;
if (avg < 3.5) below_counter++;
if (avg > 3.5) above_counter++;
if (interval_counter >= 1000000) {
cout << "Average: " << avg << " counter: " << counter << " Percentage above: "
<< (double) above_counter / (double) counter * 100.0
<< " Perc abs above counter: " << 100.0 * above_counter_this / counter
<< " r";
interval_counter = 0;
}
//usleep(1);
counter++;
interval_counter++;
}
}
rand()
是一个糟糕的生成器,它在低位尤其糟糕。执行CCD_ 2仅拾取低位。你也有可能遇到一些模偏,但我预计这种影响相对较小。
相关文章:
- 带有 -stdlib=libc++ 的 clang++ 9.0.1 找不到<optional>
- /usr/include/c++/7/cstdlib:75:15:致命错误:stdlib.h:没有这样的文件或目录 #i
- 在 xcode 上使用 stdlib.h
- 定律余弦求解c,但得到奇怪的答案
- 在 docker 容器之间传输时缺少 stdlib 符号
- 75:15:致命错误:stdlib.h:没有这样的文件或目录 #include_next <stdlib.h>
- 为什么这个自定义分配器的析构函数在 GCC/MSVS 的 stdlib 中被调用两次
- 在编译时使用 gnu++11 过滤值列表,不使用 stdlib(Arduino 环境)
- STDLIB中容器元素类型有什么要求?
- mingw/include/c++/cstdlib: stdlib.h: 没有这样的文件或目录
- Android Studio:不一致的自动包含C++ stdlib 标头
- 霍纳斯定律需要代数帮助,显示错误的答案 c++
- 从 GetProcAddress 获取的函数指针在使用 stdlib 时会使程序崩溃
- Nemiver 找不到文件 /build/glibc-LK5gWL/glibc-2.23/stdlib/random.c
- 如何从cstdlib固定stdlib.h的include_next
- Visual Studio environmant 变量未被 C++ stdlib getenv 识别
- clang:警告:编译期间未使用的参数:"-stdlib=libc++"
- Travis CI似乎是从错误的Stdlib读书
- stdlib.h's random() on MS Visual Studio 2008
- 为什么stdlib中的rand不遵循大数定律