Created
January 13, 2013 04:23
-
-
Save eienf/4522296 to your computer and use it in GitHub Desktop.
Confirm randomness for random function by sigma.
This file contains hidden or 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
// | |
// main.m | |
// CodeTest | |
// | |
// Created by [email protected] on 2013/01/13. | |
// Copyright (c) 2013 Eien Factory. All rights reserved. | |
// | |
#import <Foundation/Foundation.h> | |
#import <mach/mach_time.h> | |
#import <stdlib.h> | |
#import <ScreenSaver/ScreenSaver.h> | |
//#define REMAINDER | |
#define RANGE_MAX (10) | |
#define REPEAT (1000*1000) | |
typedef long (^funcBlock)(void); | |
double doIt(funcBlock func) { | |
uint32_t count[RANGE_MAX] = {0}; | |
const double mean = REPEAT / RANGE_MAX; | |
double sum = 0; | |
for (int i=0; i<REPEAT; i++) { | |
long value; | |
value = func(); | |
#ifdef REMAINDER | |
value = value % 10; | |
#endif | |
count[value]++; | |
} | |
for (int i = 0; i < RANGE_MAX; i++) { | |
// printf("[%d] %d\n",i,count[i]); | |
sum += pow((count[i] - mean),2); | |
} | |
// printf("%f\n", sqrt(sum/RANGE_MAX)); | |
return sqrt(sum/RANGE_MAX); | |
} | |
void doTest(const char *name, funcBlock func) | |
{ | |
double result = 0.0; | |
int repeat = 10; | |
for (int i=0; i<repeat; i++) { | |
result += doIt(func); | |
} | |
printf("%s\t%f\n",name, result/repeat); | |
} | |
int main(int argc, const char * argv[]) | |
{ | |
@autoreleasepool { | |
unsigned int seed; | |
seed = (unsigned int)time(NULL); | |
srandom(seed); | |
srand(seed); | |
doTest("arc4random()", ^long(){ | |
long value; | |
value = arc4random(); | |
#ifndef REMAINDER | |
value = ((double)value/UINT32_MAX)*(double)RANGE_MAX; | |
#endif | |
return value; | |
}); | |
doTest("random()", ^long(){ | |
long value; | |
value = random(); | |
#ifndef REMAINDER | |
value = ((double)value/RAND_MAX)*(double)RANGE_MAX; | |
#endif | |
return value; | |
}); | |
doTest("rand()", ^long(){ | |
long value; | |
value = rand(); | |
#ifndef REMAINDER | |
value = ((double)value/RAND_MAX)*(double)RANGE_MAX; | |
#endif | |
return value; | |
}); | |
doTest("SSRandomIntBetween()", ^long(){ | |
long value; | |
value = SSRandomIntBetween(0,RANGE_MAX-1); | |
return value; | |
}); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment