Skip to content

Instantly share code, notes, and snippets.

@sekrasoft
Created March 29, 2016 23:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sekrasoft/cf0e046cdfb2af3d5336b66afbbaf2e8 to your computer and use it in GitHub Desktop.
Save sekrasoft/cf0e046cdfb2af3d5336b66afbbaf2e8 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#define TEST_RAND_MAX 0xff
#define MAX 129
#define CYCLES 10000
int test_rand() {
return rand() & 0xff; // 0..255
}
int rand1(int a) {
int max = (TEST_RAND_MAX + 1ULL) / a * a - 1ULL;
int r;
do {
r = test_rand();
} while(r > max);
return r % a;
}
int rand1_naive(int a) {
return test_rand() % a;
}
int main(void) {
int results[MAX] = {};
printf("%15s", "result");
for(int i=0; i<5; ++i) printf("%6d", i);
for(int i=MAX-5; i<MAX; ++i) printf("%6d", i);
printf("\n");
for(int i=0; i<MAX*CYCLES; ++i) results[rand1(MAX)]++;
printf("%15s", "num smart");
for(int i=0; i<5; ++i) printf("%6d", results[i]);
for(int i=MAX-5; i<MAX; ++i) printf("%6d", results[i]);
printf("\n");
for(int i=0; i<MAX; ++i) results[i] = 0;
for(int i=0; i<MAX*CYCLES; ++i) results[rand1_naive(MAX)]++;
printf("%15s", "num naive");
for(int i=0; i<5; ++i) printf("%6d", results[i]);
for(int i=MAX-5; i<MAX; ++i) printf("%6d", results[i]);
return 0;
}
@sekrasoft
Copy link
Author

Программа определяет генератор случайных чисел от 0 до 255 test_rand, затем на основе него проверяет распределение rand1 и rand1_naive, генерирующие случайные числа от 0 до 129. Оказывается, что наивное взятие модуля может изменить распределение (числа 127 и 128 в случае наивного генератора выпали 5000 раз, а остальные - 10000 раз).

Вывод программы:

         result     0     1     2     3     4   124   125   126   127   128
      num smart 10101 10075  9902 10024  9790 10019  9871 10127 10231 10130
      num naive 10144 10171 10235 10327  9953 10120  9934 10091  5087  5001

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment