Created
December 17, 2011 14:10
-
-
Save cpylua/1490293 to your computer and use it in GitHub Desktop.
CRT random number generator cycle peroid test
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 <stdlib.h> | |
#include <stdio.h> | |
/** | |
* Return the cycle period | |
*/ | |
int brent_cycle_detect(int seed) { | |
int power = 1; | |
int lambda = 1; | |
int tortoise = seed; | |
int hare; | |
srand(seed); | |
hare = rand(); | |
while (hare != tortoise) { | |
if (power == lambda) { | |
tortoise = hare; | |
power *= 2; | |
lambda = 0; | |
} | |
hare = rand(); | |
lambda++; | |
} | |
return lambda; | |
} | |
void run_test(int repeat) { | |
int i; | |
int seed; | |
int period = 42; | |
printf("seed,period\n"); | |
for (i = 0; i < repeat; i++) { | |
srand(period); | |
seed = rand(); | |
period = brent_cycle_detect(seed); | |
printf("%d,%d\n", seed, period); | |
} | |
} | |
int main(int argc, char** argv) { | |
if (argc != 2) { | |
printf("usage: %s repear-count\n", argv[0]); | |
exit(-1); | |
} else { | |
int repeat = atoi(argv[1]); | |
run_test(repeat); | |
} | |
return 0; | |
} |
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
#define _CRT_RAND_S | |
#include <stdlib.h> | |
#include <stdio.h> | |
/** | |
* Return the cycle period | |
*/ | |
int brent_cycle_detect(unsigned int seed) { | |
int power = 1; | |
int lambda = 1; | |
unsigned int tortoise; | |
unsigned int hare; | |
rand_s(&tortoise); | |
rand_s(&hare); | |
while (hare != tortoise) { | |
if (power == lambda) { | |
tortoise = hare; | |
power *= 2; | |
lambda = 0; | |
} | |
rand_s(&hare); | |
lambda++; | |
} | |
return lambda; | |
} | |
void run_test(int repeat) { | |
int i; | |
int seed; | |
int period = 42; | |
printf("seed,period\n"); | |
for (i = 0; i < repeat; i++) { | |
srand(period); | |
seed = rand(); | |
period = brent_cycle_detect(seed); | |
printf("%d,%d\n", seed, period); | |
} | |
} | |
int main(int argc, char** argv) { | |
if (argc != 2) { | |
printf("usage: %s repear-count\n", argv[0]); | |
exit(-1); | |
} else { | |
int repeat = atoi(argv[1]); | |
run_test(repeat); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment