commit be34c6cda5c77df520430d10162250c9ef1ba0c7
parent dbf3c7ff51cf51ab4b2be0ec77a616bf92332a39
Author: nolash <dev@holbrook.no>
Date: Wed, 31 May 2017 01:50:43 +0200
added support for floats
Diffstat:
4 files changed, 55 insertions(+), 4 deletions(-)
diff --git a/src/benford.c b/src/benford.c
@@ -1,9 +1,20 @@
#include <math.h>
#include <stdlib.h>
+#include <stdio.h>
#include "benford.h"
-float benford_distribution[9] = {0.16, 0.14, 0.13, 0.12, 0.11, 0.10, 0.09, 0.08, 0.07};
+float benford_distribution[9] = {
+ 0.301, // 1
+ 0.176, // 2
+ 0.125, // 3
+ 0.097, // 4
+ 0.079, // 5
+ 0.067, // 6
+ 0.058, // 7
+ 0.051, // 8
+ 0.046 // 9
+};
void benford_setLead_(long int* subject, int lead) {
char order;
@@ -24,6 +35,20 @@ int benford_set(benford_t* bf, long int* number) {
return 0;
}
+int benford_setf(benford_t* bf, float* number) {
+ float intpart, decpart;
+ long int intnumber;
+
+ decpart = modff(*number, &intpart);
+ intnumber = (int)intpart;
+
+ benford_set(bf, &intnumber);
+
+ *number = (float)intnumber + decpart;
+
+ return 0;
+}
+
int benford_nextLead_(benford_t* bf) {
int i;
float ratio;
diff --git a/src/include/benford.h b/src/include/benford.h
@@ -9,6 +9,7 @@ typedef struct benford {
benford_t* benford_new();
void benford_free(benford_t* bf);
int benford_set(benford_t* bf, long int* number);
+int benford_setf(benford_t* bf, float* number);
// private functions
void benford_setLead_(long int* subject, int lead);
diff --git a/src/test/benford_test b/src/test/benford_test
Binary files differ.
diff --git a/src/test/benford_test.c b/src/test/benford_test.c
@@ -4,7 +4,7 @@
#include "benford.h"
-#define TESTCOUNT 100
+#define TESTCOUNT 200
int setLead() {
long int t = 123456;
@@ -43,7 +43,7 @@ int getLeads(int count) {
return 0;
}
-int getNumbers(int count) {
+int getInts(int count) {
int i;
long int min = 123;
@@ -65,6 +65,28 @@ int getNumbers(int count) {
return 0;
}
+int getFloats(int count) {
+ int i;
+
+ float min = 123.f;
+ float max = 123455.f;
+
+ char* leads = malloc(sizeof(char) * count);
+ getSequence(leads, count);
+
+ benford_t* bf = benford_new();
+
+ for (i = 0; i < TESTCOUNT; i++) {
+ float n = ((float)rand() / (float)RAND_MAX) * (max - min) + min;
+ float r = n;
+ benford_setf(bf, &r);
+ printf("%i: [%i?] %.3f -> %.3f\n", i, *(leads+i) + 1, n, r);
+ }
+
+ benford_free(bf);
+ return 0;
+}
+
int main() {
int e;
@@ -76,8 +98,11 @@ int main() {
if ((e = getLeads(TESTCOUNT)) > 0) {
return e;
}
- if ((e = getNumbers(TESTCOUNT)) > 0) {
+ if ((e = getInts(TESTCOUNT)) > 0) {
return e;
}
+ if ((e = getFloats(TESTCOUNT)) > 0) {
+ return e;
+ }
return 0;
}