Added ability to build custom Approx instance

This commit is contained in:
Phil Nash 2011-06-06 08:21:21 +01:00
parent cae44d8ace
commit 2fa72a47cd
2 changed files with 58 additions and 5 deletions

View File

@ -27,14 +27,44 @@ namespace Catch
/////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////
explicit Approx explicit Approx
( (
double d double value
) )
: m_epsilon( std::numeric_limits<float>::epsilon()*100 ), : m_epsilon( std::numeric_limits<float>::epsilon()*100 ),
m_scale( 1.0 ), 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 == friend bool operator ==
( (
@ -43,7 +73,7 @@ namespace Catch
) )
{ {
// Thanks to Richard Harris for his help refining this formula // 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::string toString() const
{ {
std::ostringstream oss; std::ostringstream oss;
oss << "Approx( " << m_d << ")"; oss << "Approx( " << m_value << ")";
return oss.str(); return oss.str();
} }
private: private:
double m_epsilon; double m_epsilon;
double m_scale; double m_scale;
double m_d; double m_value;
}; };
} }

View File

@ -82,3 +82,26 @@ TEST_CASE
REQUIRE( 1.234f == Approx( dMedium ) ); REQUIRE( 1.234f == Approx( dMedium ) );
REQUIRE( dMedium == Approx( 1.234f ) ); 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 );
}