2

我正在将 boost::multiprecision 库用于十进制浮点类型,并希望将两个浮点数与指定的精度进行比较。

但是, cpp_dec_float 似乎将数字与指定的精度进行比较,但还包括保护数字:

#include <iostream>

#include <boost/multiprecision/cpp_dec_float.hpp>
//#include <boost/math/special_functions.hpp>

typedef boost::multiprecision::number<boost::multiprecision::cpp_dec_float<50> > flp_type;

int main(int argc, char* argv[])
{
    // 50 decimal digits
    flp_type sqrt2("1.4142135623730950488016887242096980785696718753769");
    // Contains calculated guard digits
    flp_type result(boost::multiprecision::sqrt(flp_type("2")));

    // The 50 digits of precision actually ompare equal
    std::cout << std::setprecision(50) << sqrt2 << std::endl;
    std::cout << std::setprecision(50) << result << std::endl;
    // I want this to compare to the specified precision of the type, not the guard digits
    std::cout << (result==sqrt2) << std::endl;

    return 0;
}

输出:

1.4142135623730950488016887242096980785696718753769
1.4142135623730950488016887242096980785696718753769
0

预期的:

1.4142135623730950488016887242096980785696718753769
1.4142135623730950488016887242096980785696718753769
1

见科利鲁

我试图用precision()“截断”,但无济于事。有没有办法在不诉诸 epsilon 比较的情况下比较这两个数字?

4

2 回答 2

2

如果你去掉保护位,你会有效地削弱预期的类型的保真度。

一个万无一失的方法是使用(反)序列化,真的。

所以我建议

Live On Coliru

// Either
std::cout << std::numeric_limits<flp_type>::epsilon() << "\n";
std::cout << (abs(result-sqrt2) < std::numeric_limits<flp_type>::epsilon()) << std::endl;

// Or
result = flp_type { result.str(49, std::ios::fixed) };
std::cout << (result==sqrt2) << std::endl;

请注意,epsilon 在1e-49那里

印刷

1.4142135623730950488016887242096980785696718753769
1.4142135623730950488016887242096980785696718753769
1e-49
1
1

显然,epsilon()基于比较会显得更有效

于 2014-12-09T14:55:53.447 回答
0
bool is_equal = abs(result-sqrt2) < std::pow(10, -std::numeric_limits< flp_type >::digits10 );
于 2021-01-09T04:28:26.017 回答