//Specify the precision to compare two values bool equal(double v1, double v2, double precision); bool greater(double v1, double v2, double precision); bool less(double v1, double v2, double precision); bool equal(double v1, double v2, double precision) { double unprecision = (precision < 0) ? (-1)*precision : precision; double dt = ((v1 < v2) ? v2 : v1) - ((v1 < v2) ? v1 : v2); return (dt > unprecision) ? false : true; } bool greater(double v1, double v2, double precision) { if (equal(v1, v2, precision)) { return false; } else { return (v1 > v2) ? true : false; } } bool less(double v1, double v2, double precision) { if (equal(v1, v2, precision)) { return false; } else { return (v1 < v2) ? true : false; } } //測試代碼 #include <iostream> #include <functional> #include "../xPod_Common/common.h" using namespace std; void equal_print(double base, double precision, const double* dt, int size, const char* true_flag, const char* false_flag, function<bool(double,double,double)> func) { for (auto i=0; i<size; i++) { if (func(base, base+*(dt+i), precision)) { printf("%f %s %f, precision = %f\n", base, true_flag, base+dt[i], precision); } else { printf("%f %s %f, precision = %f\n", base, false_flag, base+dt[i], precision); } } } void equal_unit_test() { //超大數據200000正負10之內 double precision = 10; double baseVal = 200000; double dt1[] = {0.0,0.1,-0.1,0.5,-0.5,1,-1,2,-2,5,-5,10,-10,10.1,-10.1,12,-12}; cout << "Test : 200000+10 >= x >= 200000-10" << endl; equal_print(baseVal, precision, &dt1[0], sizeof(dt1)/sizeof(double), "==", "!=", &xpod_common::equal); cout << endl << endl; //高精度數據1正負0.001之內 precision = 0.001; baseVal = 1.0; double dt2[] = {0.0,0.0001,-0.0001,0.0005,-0.0005,0.001,-0.001,0.00101,-0.00101,0.0011,-0.0011,0.002,-0.002}; cout << "Test : 1+0.001 >= x >= 1-0.001" << endl; equal_print(baseVal, precision, &dt2[0], sizeof(dt2)/sizeof(double), "==", "!=", &xpod_common::equal); cout << endl << endl; //大於比較 precision = 0.1; baseVal = 100.0; double dt3[] = {-1,-0.2,-0.11,-0.10,-0.05,-0.01,0.0,0.01,0.05,0.1,0.5,1,2}; cout << "Test : Greator" << endl; equal_print(baseVal, precision, &dt3[0], sizeof(dt3)/sizeof(double), ">", "<>", &xpod_common::greater); cout << endl << endl; //小於比較 cout << "Test : Less" << endl; equal_print(baseVal, precision, &dt3[0], sizeof(dt3)/sizeof(double), "<", "<>", &xpod_common::less); } int main(int argc, char *argv[]) { //test equal equal_unit_test(); return 0; }