Created
March 29, 2016 23:29
-
-
Save sekrasoft/cf0e046cdfb2af3d5336b66afbbaf2e8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Программа определяет генератор случайных чисел от 0 до 255
test_rand
, затем на основе него проверяет распределениеrand1
иrand1_naive
, генерирующие случайные числа от 0 до 129. Оказывается, что наивное взятие модуля может изменить распределение (числа 127 и 128 в случае наивного генератора выпали 5000 раз, а остальные - 10000 раз).Вывод программы: