rand()不遵循高斯分布&中心极限定理

时间:2014-09-24 03:38:49

标签: c random

我创建了一个程序,使用rand()在C中生成重复的数字。

但重复的数字不会跟随Central Limit Theorem

任何人都可以解决这个rand()bug问题,或者除了使用rand()C库生成更好的随机数之外还有其他选择吗?

这是屏幕截图:enter image description here

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#include <windows.h>


#define TOTAL_THROW 10000000

typedef enum _COINTOSS {
    UNDEFINED = 0,
    HEAD = 1,
    TAIL = 2
} COINTOSS;

COINTOSS toss_coin () {
    int x = rand() % 2;
    if (x == 0) return HEAD;
    else if (x == 1) return TAIL;
}

void main () {
    int x, i, j, v1 = 0, v2 = 200, total = 0;
    int head_range[25] = {0};
    int tail_range[25] = {0};
    int no_range = 0;
    int count = 0;
    int repeated = 0;
    COINTOSS previos_toss = UNDEFINED;
    COINTOSS current_toss;

    srand(time(NULL));

    for (i=0; i<TOTAL_THROW; i++) {
        current_toss = toss_coin();             // current toss
        if (previos_toss == current_toss) {
            count++;
        } else {
            if (current_toss == HEAD) head_range[count] += 1;
            else if (current_toss == TAIL) tail_range[count] += 1;


            previos_toss = current_toss;
            count = 0;
        }

    }

    for (i=24; i>=0; i--) {
        printf("+%d = %d\n", i+1, head_range[i]);
    }

    puts("________________\n");

    for (i=0; i<25; i++) {
        printf("-%d = %d\n", i+1, tail_range[i]);
    }

    printf("\nTOTAL_THROW: %d\n", TOTAL_THROW);


    printf("\nPress [ENTER] to exit. . .");
    getchar();
}

1 个答案:

答案 0 :(得分:4)

您的问题是使用模数将随机数输入所需的范围,该范围使用较低的位(它是经典的问题):

int x = rand() % 2;

rand()(a linear congruential generator(LCG))的低位不像高位那样随机。这适用于所有LCG,无论图书馆或语言如何。

对于[0..N]的范围,你应该做这样的事情(使用高位):

int r = rand() / ( RAND_MAX / N + 1 );