benfordgenerator

C Library and cli application to generate number sequences with first digits distributed according to Benford's Law
git clone git://git.defalsify.org/libbenford.git
Info | Log | Files | Refs

benford_test.c (1815B)


      1 #include <stdio.h>
      2 #include <stdlib.h>
      3 #include <time.h>
      4 
      5 #include "benford.h"
      6 
      7 #define TESTCOUNT 200
      8 
      9 int setLead() {
     10 	long int t = 123456;
     11 	int d = 4;
     12 	benford_setLead_(&t, d);
     13 	
     14 	if (t != 323456) {
     15 		return -1;
     16 	}
     17 	
     18 	return 0;
     19 }
     20 
     21 void getSequence(char *leads, int count) {
     22 	int i;
     23 	benford_t* bf = benford_new();
     24 	for (i = 0; i < count; i++) {
     25 		*(leads+i) = benford_nextLead_(bf);
     26 	}
     27 	benford_free(bf);
     28 }
     29 
     30 int getLeads(int count) {
     31 	int i;
     32 	char *res = calloc(sizeof(int), count);
     33 	int *rescount = calloc(sizeof(int), 9);
     34 	
     35 	getSequence(res, count);
     36 	
     37 	for (i = 0; i < count; i++) {
     38 		(*(rescount + (*(res+i))))++;
     39 	}
     40 	for (i = 0; i < 9; i++) {
     41 		printf("%i: %i\n", i, *(rescount+i));
     42 	}
     43 	return 0;
     44 }
     45 
     46 int getInts(int count) {
     47 	int i;
     48 	
     49 	long int min = 123;
     50 	long int max = 912346789;
     51 	
     52 	char* leads = malloc(sizeof(char) * count);
     53 	getSequence(leads, count);
     54 	
     55 	benford_t* bf = benford_new();
     56 	
     57 	for (i = 0; i < TESTCOUNT; i++) {
     58 		long int n = (rand() % (max - min)) + min + 1;
     59 		long int r = n;
     60 		benford_set(bf, &r);
     61 		printf("%i: [%i?] %li -> %li\n", i, *(leads+i) + 1, n, r);
     62 	}
     63 	
     64 	benford_free(bf);
     65 	return 0;
     66 }
     67 
     68 int getFloats(int count) {
     69 	int i;
     70 	
     71 	float min = 123.f;
     72 	float max = 123455.f;
     73 	
     74 	char* leads = malloc(sizeof(char) * count);
     75 	getSequence(leads, count);
     76 	
     77 	benford_t* bf = benford_new();
     78 	
     79 	for (i = 0; i < TESTCOUNT; i++) {
     80 		float n = ((float)rand() / (float)RAND_MAX) * (max - min) + min;
     81 		float r = n;
     82 		benford_setf(bf, &r);
     83 		printf("%i: [%i?] %.3f -> %.3f\n", i, *(leads+i) + 1, n, r);
     84 	}
     85 	
     86 	benford_free(bf);
     87 	return 0;
     88 }
     89 
     90 int main() {
     91 	int e;
     92 	
     93 	srand(clock());
     94 	
     95 	if ((e = setLead()) > 0) {
     96 		return e;
     97 	}
     98 	if ((e = getLeads(TESTCOUNT)) > 0) {
     99 		return e;
    100 	}
    101 	if ((e = getInts(TESTCOUNT)) > 0) {
    102 		return e;
    103 	} 
    104 	if ((e = getFloats(TESTCOUNT)) > 0) {
    105 		return e;
    106 	}
    107 	return 0;
    108 }