更新:您现在可以 在 Catch2 中指定精度。以下适用于旧版本的 Catch2。
看起来精度在 Catch2 本身中是硬编码的:
std::string StringMaker<float>::convert(float value) {
return fpToString(value, 5) + 'f';
}
std::string StringMaker<double>::convert(double value) {
return fpToString(value, 10);
}
有两个选项可以解决此问题:
选项 1:修改 Catch2
如果你修改它,你可以让它显示你想要的(注意:<limits>
已经包含在 catch 中,所以我将使用std::numeric_limits
):
std::string StringMaker<float>::convert(float value) {
return fpToString(value, std::numeric_limits<float>::max_digits10) + 'f';
}
std::string StringMaker<double>::convert(double value) {
return fpToString(value, std::numeric_limits<double>::max_digits10);
}
可以采用更复杂的方法将其作为用户可以设置的参数,而不是将其硬编码为不同的半任意值,但这只是一个问答,而不是拉取请求。;-)
选项 2:以更高的精度自行记录
如果您在调用INFO( FullPrecision(d) );
之前添加REQUIRE()
,您将获得完整的精确打印,但仅在测试用例失败时。(见FullPrecision()
下面的定义。)
这两个变化都在这里演示:
#define CATCH_CONFIG_MAIN // This tells Catch to provide a main() - only do this in one cpp file
#include "catch.hpp"
#include <limits>
#include <sstream>
#include <iomanip>
double GetDouble() { return std::numeric_limits<double>::epsilon(); }
std::string FullPrecision( double d )
{
auto s = std::ostringstream{};
s << std::setprecision( std::numeric_limits<double>::max_digits10 ) << d;
return s.str();
}
TEST_CASE( "Double, double, toil and trouble", "[double]" )
{
const auto d = GetDouble();
INFO( FullPrecision(d) );
REQUIRE( 0.0 == d );
}
打印:
prog.cc:20: FAILED:
REQUIRE( 0.0 == d )
with expansion:
0.0 == 0.00000000000000022
with message:
2.2204460492503131e-16
修改 Catch2 会导致扩展0.0 == 0.00000000000000022
,添加INFO()
会导致消息2.2204460492503131e-16
。
看它直播Wandbox。