From 540c07677f84c2680c808ecfb6be4ad6bb61237e Mon Sep 17 00:00:00 2001 From: Sam Lidder Date: Sat, 18 Aug 2012 01:30:40 -0400 Subject: [PATCH] add extra tests for comparing floating point values - __equals() function is overloaded to handle comparisons between double and vector according to TopCoder standards --- src/com/dogcows/resources/C++Driver | 37 ++++++++++++++++++++++++++++- 1 file changed, 36 insertions(+), 1 deletion(-) 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; -- 2.43.0