From: Sam Lidder Date: Sat, 18 Aug 2012 05:30:40 +0000 (-0400) Subject: add extra tests for comparing floating point values X-Git-Tag: v0.3.3~8 X-Git-Url: https://git.brokenzipper.com/gitweb?a=commitdiff_plain;h=540c07677f84c2680c808ecfb6be4ad6bb61237e;p=chaz%2Fvimcoder add extra tests for comparing floating point values - __equals() function is overloaded to handle comparisons between double and vector according to TopCoder standards --- diff --git a/src/com/dogcows/resources/C++Driver b/src/com/dogcows/resources/C++Driver index 142fdac..9ca8579 100644 --- a/src/com/dogcows/resources/C++Driver +++ b/src/com/dogcows/resources/C++Driver @@ -1,6 +1,8 @@ #include "$CLASSNAME$.cc" +#include +#include #include #include #include @@ -12,6 +14,7 @@ using namespace std; +const static double __EPSILON = 1e-9; static double __time = 0.0; static void __timer_start() @@ -99,6 +102,38 @@ std::istream& operator >> (std::istream& in, std::vector& vec) return in; } +template +bool __equals(const T& actual, const T& expected) +{ + return actual == expected; +} + +bool __equals(double actual, double expected) +{ + if (std::abs(actual - expected) < __EPSILON) + { + return true; + } + else + { + double minimum = std::min(expected * (1.0 - __EPSILON), expected * (1.0 + __EPSILON)); + double maximum = std::max(expected * (1.0 - __EPSILON), expected * (1.0 + __EPSILON)); + return actual > minimum && actual < maximum; + } +} + +bool __equals(const std::vector& actual, const std::vector& expected) +{ + if (actual.size() != expected.size()) + return false; + + for (size_t i = 0; i < actual.size(); ++i) + if (!__equals(actual[i], expected[i])) + return false; + + return true; +} + int main(int argc, char* argv[]) { @@ -127,7 +162,7 @@ int main(int argc, char* argv[]) double __t = __timer_stop(); - if (__actual == __expected) + if (__equals(__actual, __expected)) { std::cout << "[PASS] in " << __t << " seconds." << std::endl; ++__pass;