How to use floating point tolerances in the Catch framework?

China☆狼群 提交于 2019-12-03 10:45:35

问题


I'm using the Catch test framework.

In the introductory blog post the author mentions the following feature:

  • Floating point tolerances supported in an easy to use way

I couldn't find any documentation on how to do this. How is this done in Catch?


回答1:


It's simple. There is a class called Approx that lets you do this test in a very readable manner:

#include <limits>
TEST_CASE("demo/approx", "Approx demo") {
    double a = 1.0;
    double b = a + std::numeric_limits<double>::epsilon();
    REQUIRE_FALSE(b == a);
    REQUIRE(b == Approx(a));
}

The tolerance can be changed by using the member functions epsilon() and scale() of the Approx object, like so: Approx(a).epsilon(e).




回答2:


The tolerance is has been customizable since Apr 2011. Approx has two member functions for this: epsilon() and scale(). For example:

REQUIRE(a == Approx(b).epsilon(my_eps));

The tolerance is ε × (scale+max(|a|, |b|)), where scale defaults to 1, so this will pass:

REQUIRE((2+2) == Approx(5).epsilon(0.17));



回答3:


I know this is an old question, but I just stumbled upon the same problem and found a simple solution. In the Catch.hpp header file where the Approx class is defined (line 2045 at the time of writing), just add the following constructor:

class Approx {
public:
    explicit Approx( double value )
    :   m_epsilon( std::numeric_limits<float>::epsilon()*100 ),
        m_scale( 1.0 ),
        m_value( value )
    {}

    explicit Approx( double value, double epsilon ) // <- New constructor
    :   m_epsilon( epsilon ),
        m_scale( 1.0 ),
        m_value( value )
    {}

Now you can do this:

TEST_CASE("demo/approx", "Approx demo") {
    double myTol = 0.1;
    double a = 1.0;
    double b = a + myTol;
    REQUIRE_FALSE(a == b);
    REQUIRE(a == Approx(b, myTol)); 
}


来源:https://stackoverflow.com/questions/6718343/how-to-use-floating-point-tolerances-in-the-catch-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!