X-Git-Url: https://git.ucc.asn.au/?a=blobdiff_plain;f=server%2Fdata.c;h=19828bc0492b4c5e93719d06f1e9f3f348ec04f4;hb=0654fb285c91da103314610cd4f27295e3da38f3;hp=edfd4c3d388c74d7236469c7cde3db0274c184d1;hpb=19c48bb0707a0a92aa713e125cbd070295621383;p=matches%2FMCTX3420.git diff --git a/server/data.c b/server/data.c index edfd4c3..19828bc 100644 --- a/server/data.c +++ b/server/data.c @@ -356,3 +356,51 @@ DataFormat Data_GetFormat(FCGIValue * fmt) } return JSON; } + +/** + * Binary search for index of a double in an array + * @param value - The value + * @param x - The array + * @param size - Sizeof the array + */ +int FindClosest(double value, double x[], int size) +{ + int upper = size-1; + int lower = 0; + int index = 0; + while (upper - lower > 1) + { + index = lower + ((upper - lower)/2); + double look = x[index]; + if (look > value) + upper = index; + else if (look < value) + lower = index; + else + return index; + } + + if (x[index] > value && index > 0) + --index; + return index; + +} + +/** + * Get calibrated value by interpolation in array y + * @param value - Raw measured value + * @param x - x values (raw values) of the data + * @param y - calibrated values + * @param size - Number of values in the arrays + * @returns interpolated calibrated value + */ +double Data_Calibrate(double value, double x[], double y[], int size) +{ + int i = FindClosest(value, x, size); + if (i >= size-1) + { + i = size-2; + } + double dist = (value - x[i])/(x[i+1] - x[i]); + return y[i] + dist*(y[i+1]-y[i]); +}