From 2fa72a47cd4b8094f6c6d987ba37968747aa790a Mon Sep 17 00:00:00 2001 From: Phil Nash Date: Mon, 6 Jun 2011 08:21:21 +0100 Subject: [PATCH] Added ability to build custom Approx instance --- include/internal/catch_approx.hpp | 40 +++++++++++++++++++++++++++---- projects/SelfTest/ApproxTests.cpp | 23 ++++++++++++++++++ 2 files changed, 58 insertions(+), 5 deletions(-) diff --git a/include/internal/catch_approx.hpp b/include/internal/catch_approx.hpp index 8a98a735..04e63df9 100644 --- a/include/internal/catch_approx.hpp +++ b/include/internal/catch_approx.hpp @@ -27,14 +27,44 @@ namespace Catch /////////////////////////////////////////////////////////////////////////// explicit Approx ( - double d + double value ) : m_epsilon( std::numeric_limits::epsilon()*100 ), m_scale( 1.0 ), - m_d( d ) + m_value( value ) { } + /////////////////////////////////////////////////////////////////////////// + Approx + ( + const Approx& other + ) + : m_epsilon( other.m_epsilon ), + m_scale( other.m_scale ), + m_value( other.m_value ) + { + } + + /////////////////////////////////////////////////////////////////////////// + static Approx custom + () + { + return Approx( 0 ); + } + + /////////////////////////////////////////////////////////////////////////// + Approx operator() + ( + double value + ) + { + Approx approx( value ); + approx.epsilon( m_epsilon ); + approx.scale( m_scale ); + return approx; + } + /////////////////////////////////////////////////////////////////////////// friend bool operator == ( @@ -43,7 +73,7 @@ namespace Catch ) { // Thanks to Richard Harris for his help refining this formula - return fabs( lhs - rhs.m_d ) < rhs.m_epsilon * (rhs.m_scale + (std::max)( fabs(lhs), fabs(rhs.m_d) ) ); + return fabs( lhs - rhs.m_value ) < rhs.m_epsilon * (rhs.m_scale + (std::max)( fabs(lhs), fabs(rhs.m_value) ) ); } /////////////////////////////////////////////////////////////////////////// @@ -101,14 +131,14 @@ namespace Catch std::string toString() const { std::ostringstream oss; - oss << "Approx( " << m_d << ")"; + oss << "Approx( " << m_value << ")"; return oss.str(); } private: double m_epsilon; double m_scale; - double m_d; + double m_value; }; } diff --git a/projects/SelfTest/ApproxTests.cpp b/projects/SelfTest/ApproxTests.cpp index cdab6019..f9addb4e 100644 --- a/projects/SelfTest/ApproxTests.cpp +++ b/projects/SelfTest/ApproxTests.cpp @@ -82,3 +82,26 @@ TEST_CASE REQUIRE( 1.234f == Approx( dMedium ) ); REQUIRE( dMedium == Approx( 1.234f ) ); } + +/////////////////////////////////////////////////////////////////////////////// +TEST_CASE +( + "./succeeding/Approx/custom", + "Use a custom approx" +) +{ + double d = 1.23; + + Approx approx = Approx::custom().epsilon( 0.005 ); + + REQUIRE( d == approx( 1.23 ) ); + REQUIRE( d == approx( 1.22 ) ); + REQUIRE( d == approx( 1.24 ) ); + REQUIRE( d != approx( 1.25 ) ); + + REQUIRE( approx( d ) == 1.23 ); + REQUIRE( approx( d ) == 1.22 ); + REQUIRE( approx( d ) == 1.24 ); + REQUIRE( approx( d ) != 1.25 ); +} +